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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@ public struct ConnectionDestination: Equatable, Sendable {
case verifyIdentity
}

// A linked SSH profile is named by the servers it dials, so moving the profile moves the destination.
public enum Tunnel: Equatable, Sendable {
case none
case profile(UUID)
case ssh(server: Endpoint, jumps: [Endpoint])
}

Expand Down Expand Up @@ -100,8 +100,6 @@ public struct ConnectionDestination: Equatable, Sendable {
switch tunnel {
case .none:
return "none"
case .profile(let id):
return "profile:" + id.uuidString.lowercased()
case .ssh(let server, let jumps):
return ([server] + jumps)
.map { Self.normalizedHost($0.host) + ":" + String($0.port) }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ struct ConnectionDestinationTests {
#expect(saved.digest != crafted.digest)
}

@Test("Engine, TLS, SSH server, jump host, SSH profile and any plugin field each change the digest")
@Test("Engine, TLS, SSH server, jump host and any plugin field each change the digest")
func everyRoutingInputChangesTheDigest() {
let jumpless = ConnectionDestination.Tunnel.ssh(
server: .init(host: "bastion.prod", port: 22), jumps: []
Expand All @@ -46,7 +46,6 @@ struct ConnectionDestinationTests {
jumps: [.init(host: "hop.attacker.example", port: 22)]
)
),
Self.production(transport: .verifyIdentity, tunnel: .profile(UUID())),
Self.production(transport: .verifyIdentity, tunnel: jumpless, fields: ["esSkipTLSVerify": "true"]),
Self.production(transport: .verifyIdentity, tunnel: jumpless, fields: ["someFutureField": "x"]),
]
Expand Down
7 changes: 4 additions & 3 deletions apple/TablePro/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,10 @@ class AppDelegate: NSObject, NSApplicationDelegate {
KeyRepeatFilter.shared.install()
TableClickFocus.shared.install()
RecentTabSwitcherController.installEditorKeyClaim()
let syncSettings = AppSettingsStorage.shared.loadSync()
let passwordSyncExpected = syncSettings.enabled && syncSettings.syncConnections && syncSettings.syncPasswords
AppStorageEnvironment.shared.defaults.set(passwordSyncExpected, forKey: KeychainHelper.passwordSyncEnabledKey)
AppStorageEnvironment.shared.defaults.set(
AppSettingsStorage.shared.loadSync().syncsPasswords,
forKey: KeychainHelper.passwordSyncEnabledKey
)
DatabaseManager.shared.startObservingSystemEvents()
DatabaseManager.shared.tabStatePersister = SessionTabStatePersister()

Expand Down
3 changes: 3 additions & 0 deletions apple/TablePro/Core/Database/ConnectionTunnelError.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ enum ConnectionTunnelError: Error, LocalizedError, Equatable {
case remoteFileUnsupported(String)
case remoteFilePathMissing
case srvLookupBehindTunnel
case sshProfileMoved

static func refusal(for connection: DatabaseConnection) -> ConnectionTunnelError? {
guard connection.enabledTunnelKinds.contains(where: { $0 != .remoteFile && $0 != .remoteDatabaseSession })
Expand Down Expand Up @@ -36,6 +37,8 @@ enum ConnectionTunnelError: Error, LocalizedError, Equatable {
An SRV record names servers the tunnel cannot reach, so the connection would go around it. Turn the tunnel \
off, or list the servers under Hosts and turn off Use SRV Record.
""")
case .sshProfileMoved:
return String(localized: "The SSH profile this connection uses now points to another server. Click Reconnect in its window to use it.")
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,10 @@ extension DatabaseManager {
_ connection: DatabaseConnection,
passwordOverride: String? = nil,
sshPasswordOverride: String? = nil,
trigger: ConnectTrigger = .request
trigger: ConnectTrigger = .request,
adoptsSSHProfileEdits: Bool = false
) async throws {
/// An installed driver is only a reason to skip while it still answers. A reconnect that
/// gave up leaves one behind, and returning here made Reconnect a button that did nothing
/// on the one connection that needed it. A driver nobody has heard from in a while is the
/// same problem one step earlier, which is what the check answers.
// A driver is a reason to skip only while it answers: one a reconnect gave up on made Reconnect do nothing.
await verifyBeforeUse(connection.id)
if let session = activeSessions[connection.id], session.driver != nil, session.liveness == .live {
return
Expand All @@ -26,7 +24,8 @@ extension DatabaseManager {
connection,
passwordOverride: passwordOverride,
sshPasswordOverride: sshPasswordOverride,
trigger: trigger
trigger: trigger,
adoptsSSHProfileEdits: adoptsSSHProfileEdits
)
}
}
Expand Down
4 changes: 3 additions & 1 deletion apple/TablePro/Core/Database/DatabaseManager+Health.swift
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ extension DatabaseManager {
}
// A refusal that needs a person gets the same answer on every retry.
if error is EnvVarReferenceConsentError || error is PreConnectScriptConsentError
|| error is LocalCredentialConsentError {
|| error is LocalCredentialConsentError || error is ConnectionTunnelError {
return .stop(ConnectionFailureClassifier.info(for: error))
}
// The lease renewal stops on the same Vault errors; an unreachable or failing Vault is worth another try.
Expand Down Expand Up @@ -293,6 +293,7 @@ extension DatabaseManager {
}
let connectionForDriver = try await buildEffectiveConnection(
for: connection,
pinnedSSHRoute: session.connection.destinationTunnel,
deadline: deadline,
ownsAttempt: { self.isCurrentAttempt(generation, for: connectionId) }
)
Expand Down Expand Up @@ -476,6 +477,7 @@ extension DatabaseManager {
let deadline = ConnectionDeadline(configuredSeconds: connection.connectTimeoutSeconds)
let effectiveConnection = try await buildEffectiveConnection(
for: connection,
pinnedSSHRoute: session.connection.destinationTunnel,
deadline: deadline,
ownsAttempt: { self.isCurrentAttempt(generation, for: sessionId) }
)
Expand Down
16 changes: 15 additions & 1 deletion apple/TablePro/Core/Database/DatabaseManager+SSH.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

import Foundation

import TableProConnectionLibrary
import TableProSSHConfig
import TableProSSHTransport

Expand All @@ -16,13 +17,15 @@ extension DatabaseManager {
// `sshPasswordOverride` is the password Test Connection typed, used instead of the stored one.
// `ownsAttempt` is asked with nothing suspending before the tunnel is created: tunnels are keyed by
// connection, and creating one closes whatever a newer attempt opened under the same id.
// `pinnedSSHRoute` is the route an open session dialed: a linked profile moved since then is refused, not followed.
internal func buildEffectiveConnection(
for original: DatabaseConnection,
sshPasswordOverride: String? = nil,
pinnedSSHRoute: ConnectionDestination.Tunnel? = nil,
deadline: ConnectionDeadline,
ownsAttempt: () -> Bool = { true }
) async throws -> DatabaseConnection {
var connection = SSHProfileStorage.shared.refreshingLinkedProfile(original)
var connection = try routedThroughLinkedProfile(original, pinnedSSHRoute: pinnedSSHRoute)
// Only the tunnel this connect opens says it secures the transport or names the server behind it; a saved or
// imported field never does.
connection.additionalFields[DatabaseConnection.tunnelSecuresTransportKey] = nil
Expand Down Expand Up @@ -127,6 +130,17 @@ extension DatabaseManager {
)
}

internal func routedThroughLinkedProfile(
_ connection: DatabaseConnection,
pinnedSSHRoute: ConnectionDestination.Tunnel?
) throws -> DatabaseConnection {
let routed = SSHProfileStorage.shared.refreshingLinkedProfile(connection)
if let pinnedSSHRoute, case .profile = routed.sshTunnelMode, routed.destinationTunnel != pinnedSSHRoute {
throw ConnectionTunnelError.sshProfileMoved
}
return routed
}

// MARK: - SSH Tunnel Recovery

func handleSSHTunnelDied(connectionId: UUID) async {
Expand Down
67 changes: 58 additions & 9 deletions apple/TablePro/Core/Database/DatabaseManager+Sessions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ extension DatabaseManager {
_ requestedConnection: DatabaseConnection,
passwordOverride incomingPasswordOverride: String? = nil,
sshPasswordOverride: String? = nil,
trigger: ConnectTrigger = .request
trigger: ConnectTrigger = .request,
adoptsSSHProfileEdits: Bool = false
) async throws {
let connection = resolvedConnectionDefinition(for: requestedConnection)

Expand Down Expand Up @@ -49,6 +50,12 @@ extension DatabaseManager {
let effectiveQueryTimeoutSeconds = prepareConnectingSession(for: connection)
lastActiveSessionId = connection.id

let (routedConnection, pinnedSSHRoute) = try pinSSHRoute(
for: connection,
adoptsSSHProfileEdits: adoptsSSHProfileEdits,
attempt: attempt
)

let (resolvedConnection, dialledConnection) = try await authorizeConnect(
connection,
trigger: trigger,
Expand Down Expand Up @@ -76,6 +83,7 @@ extension DatabaseManager {
effectiveConnection = try await buildEffectiveConnectionReportingStages(
for: dialledConnection,
sshPasswordOverride: sshPasswordOverride,
pinnedSSHRoute: pinnedSSHRoute,
deadline: deadline,
attempt: (attempt, connection.id)
)
Expand Down Expand Up @@ -148,9 +156,10 @@ extension DatabaseManager {
// Batch all session mutations into a single write to fire objectWillChange once.
if var session = activeSessions[connection.id] {
session.connection = successfulConnectionRecord(
from: connection,
from: routedConnection,
preservingSessionFieldsFrom: session.connection
)
dialedConnections[connection.id] = routedConnection
session.commitMode = session.connection.commitMode
session.driver = driver
session.status = driver.status
Expand All @@ -163,18 +172,15 @@ extension DatabaseManager {
markSessionVerified(connection.id)
if let passwordOverride, !connection.usesIAMToken {
session.cachedPassword = passwordOverride
/// Only a password that actually authenticated is shared with the other
/// connections on this profile. Caching the prompt's answer before the connect
/// meant one mistyped password locked every one of them out until a relaunch,
/// because the prompt never came back.
// Only once it authenticated: a mistyped answer shared with the profile locked every connection out.
if promptsForPassword {
promptedPasswords[promptCacheKey] = passwordOverride
}
}
setSession(session, for: connection.id)
}

/// Before `finish`, so the clear is still the current attempt's to make.
// Before `finish`, so the clear is still the current attempt's to make.
clearConnectionStage(for: connection.id)
connectionAttempts.finish(attempt, for: connection.id)

Expand Down Expand Up @@ -217,7 +223,7 @@ extension DatabaseManager {
}
// A session's answer is reused only while the connection still dials where it was typed for.
let session = activeSessions[connection.id]
let sessionPassword = session?.connection.destination.digest == connection.destination.digest
let sessionPassword = session?.connection.destination.digest == connection.dialedDestination.digest
? session?.cachedPassword
: nil
if let cached = promptedPasswords[promptCacheKey] ?? sessionPassword {
Expand Down Expand Up @@ -247,7 +253,7 @@ extension DatabaseManager {
let sharedByProfile = connection.credentialMode.profileId != nil
return PromptedPasswordKey(
owner: ConnectionCredentialResolver.credentialOwner(for: connection),
destination: sharedByProfile ? "" : connection.destination.digest
destination: sharedByProfile ? "" : connection.dialedDestination.digest
)
}

Expand Down Expand Up @@ -650,6 +656,8 @@ extension DatabaseManager {
guard let previous = session(for: connectionId) else {
throw DatabaseError.notConnected
}
// Refused before anything is torn down, so the session stays on the server it dialed.
_ = try routedThroughLinkedProfile(previous.connection, pinnedSSHRoute: previous.connection.destinationTunnel)
// The reconnect would end a live transaction; one on a connection that already stopped answering is gone anyway.
if previous.liveness == .live, await browsedDriverHoldsTransaction(previous.driver, for: connectionId) {
throw DatabaseError.connectionFailed(
Expand Down Expand Up @@ -777,6 +785,8 @@ extension DatabaseManager {
/// first: `MainContentCoordinator.teardown()` clears them from memory and only the window-close
/// path saves on its way out, which is how a disconnect used to take a window's tabs with it.
func disconnectSession(_ sessionId: UUID, origin: SessionDisconnectOrigin = .appManaged) async {
// Before the lookup: closing the window of a connect that failed has no session to end, only the route.
dialedConnections[sessionId] = nil
let lifecycleLogger = Logger(subsystem: "com.TablePro", category: "NativeTabLifecycle")
guard let session = activeSessions[sessionId] else {
lifecycleLogger.info(
Expand Down Expand Up @@ -1126,10 +1136,48 @@ extension DatabaseManager {
}
}

// Read once, before any approval is asked for, so the approvals and the dial name one route. A session that
// already dialed keeps its route under its window; only that window's Connect takes up a profile edit.
private func pinSSHRoute(
for connection: DatabaseConnection,
adoptsSSHProfileEdits: Bool,
attempt: Int
) throws -> (routed: DatabaseConnection, pinned: ConnectionDestination.Tunnel) {
let routed = SSHProfileStorage.shared.refreshingLinkedProfile(connection)
let kept = adoptsSSHProfileEdits
? nil
: activeSessions[connection.id].flatMap { $0.effectiveConnection == nil ? nil : $0.connection }
?? dialedConnections[connection.id]
let pinned = kept?.destinationTunnel ?? routed.destinationTunnel
// A deleted profile leaves its last server inline, so a session dialed through one is checked as well.
guard Self.followsSSHProfile(routed) || kept.map(Self.followsSSHProfile) == true,
routed.destinationTunnel != pinned
else { return (routed, pinned) }
let error = ConnectionTunnelError.sshProfileMoved
if connectionAttempts.isCurrent(attempt, for: connection.id) {
clearConnectionStage(for: connection.id)
}
// A session that dialed stays, unreachable, under its window; an entry this attempt made goes.
if let driver = activeSessions[connection.id]?.driver {
let info = ConnectionFailureClassifier.info(for: error)
updateSession(connection.id) { $0.status = .error(info.message) }
markSessionUnreachable(connection.id, startedWith: driver, info: info)
} else {
finalizeConnectionFailure(for: connection.id, cancelled: false, error: error, attempt: attempt)
}
throw error
}

private static func followsSSHProfile(_ connection: DatabaseConnection) -> Bool {
if case .profile = connection.sshTunnelMode { return true }
return false
}

// The proxy reports its download as a stage of this attempt.
private func buildEffectiveConnectionReportingStages(
for resolvedConnection: DatabaseConnection,
sshPasswordOverride: String?,
pinnedSSHRoute: ConnectionDestination.Tunnel,
deadline: ConnectionDeadline,
attempt: (number: Int, connectionId: UUID)
) async throws -> DatabaseConnection {
Expand All @@ -1139,6 +1187,7 @@ extension DatabaseManager {
try await buildEffectiveConnection(
for: resolvedConnection,
sshPasswordOverride: sshPasswordOverride,
pinnedSSHRoute: pinnedSSHRoute,
deadline: deadline,
ownsAttempt: { !self.isAttemptCancelled(attempt.number, for: attempt.connectionId) }
)
Expand Down
4 changes: 4 additions & 0 deletions apple/TablePro/Core/Database/DatabaseManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,10 @@ final class DatabaseManager: ObservableObject {
/// before touching shared session state and discards its driver when it lost.
internal var connectionAttempts = ConnectionAttemptRegistry()

// What each connection last dialed, kept through a failed connect so an unattended one cannot follow an SSH profile
// edit under the window; a disconnect ends it, and the window's own Connect replaces it.
internal var dialedConnections: [UUID: DatabaseConnection] = [:]

/// The step each in-flight connect last reported, so a window that joins one already running
/// can seed itself. `AppEvents.connectionStageChanged` is a `PassthroughSubject`, so it holds
/// nothing: an observer built after a step was sent could only report the generic fallback,
Expand Down
2 changes: 1 addition & 1 deletion apple/TablePro/Core/Database/EnvVarReferenceConsent.swift
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ internal final class EnvVarReferenceConsent {
EnvVarReferenceQuestion(
connectionName: connection.name,
names: EnvVarResolver.referencedNames(in: connection).sorted(),
destination: connection.destinationSummary,
destination: SSHProfileStorage.shared.refreshingLinkedProfile(connection).destinationSummary,
origin: connection.origin
)
}
Expand Down
2 changes: 1 addition & 1 deletion apple/TablePro/Core/Database/LocalCredentialConsent.swift
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ internal final class LocalCredentialConsent {
uses: ConnectionFieldCatalog.localCredentialUses(in: connection.additionalFields).map { use in
describe(use, fields: fields)
},
destination: connection.destinationSummary,
destination: SSHProfileStorage.shared.refreshingLinkedProfile(connection).destinationSummary,
origin: connection.origin
)
}
Expand Down
25 changes: 25 additions & 0 deletions apple/TablePro/Core/Plugins/PluginManager+Lifecycle.swift
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,29 @@ extension PluginManager {
Self.logger.info("Uninstalled plugin '\(id)'")
needsRestart = true
}

// Only a bundle in the user's plugins folder: one inside the app breaks its seal, and no registry install brings
// a bundled engine back.
func canRemoveRejectedPlugin(_ plugin: RejectedPlugin) -> Bool {
let bundle = plugin.url.standardizedFileURL
guard !bundle.lastPathComponent.isEmpty, bundle.lastPathComponent != "/" else { return false }
// The folder, not the bundle, is resolved: a bundle linked in from a build folder is still the user's to remove.
let folder = bundle.deletingLastPathComponent().resolvingSymlinksInPath().path
return folder == userPluginsDir.standardizedFileURL.resolvingSymlinksInPath().path
}

// To the Trash rather than deleted, so a mistaken removal can be put back.
func removeRejectedPlugin(
_ plugin: RejectedPlugin,
moveToTrash: (URL) throws -> Void = { try FileManager.default.trashItem(at: $0, resultingItemURL: nil) }
) throws {
guard canRemoveRejectedPlugin(plugin) else { throw PluginError.cannotUninstallBuiltIn }
if FileManager.default.fileExists(atPath: plugin.url.path) {
do {
try moveToTrash(plugin.url)
} catch CocoaError.fileNoSuchFile {}
}
removeFromRejected(url: plugin.url)
Self.logger.info("Moved rejected plugin '\(plugin.name, privacy: .public)' to the Trash")
}
}
Loading
Loading