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
23 changes: 15 additions & 8 deletions apple/Plugins/MSSQLDriverPlugin/FreeTDSConnection.swift
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,13 @@ nonisolated private func freetdsRecordMessage(_ message: MSSQLServerMessage, for
return
}
let key = freetdsConnectionKey(dbproc)
// db-lib hands a login's messages the DBPROCESS it is still building, which has no gate until it is adopted and is
// freed when the login fails, so the first refusal goes where a failed open reads its reason.
let refusesLogin = message.isError && freetdsGate(forKey: key) == nil
freetdsErrors.withLock { state in
if refusesLogin, state.global.isEmpty {
state.global = message.text
}
state.perConnection[key, default: FreeTDSDiagnostics()].record(message)
}
}
Expand Down Expand Up @@ -342,24 +348,23 @@ nonisolated final class FreeTDSConnection: @unchecked Sendable {
defer { dbloginfree(login) }
try configure(login)

let opened: UnsafeMutablePointer<DBPROCESS>?
let opened: (proc: UnsafeMutablePointer<DBPROCESS>?, refusal: String)
do {
opened = try freetdsConfigFile.withEntry(
entry,
waitingAtMost: TimeInterval(deadline.remainingMilliseconds) / 1_000,
givingUpWhen: { attempt.isSettled }
) {
guard !attempt.isSettled else { throw CancellationError() }
freetdsClearError(for: nil)
return try open(login, serverName: entry.name, deadline: deadline)
}
} catch MSSQLFreeTDSConfigError.nameInUse {
throw MSSQLCoreError.connectionTimedOut(isKerberos: options.authMethod == .windows)
} catch let error as MSSQLFreeTDSConfigError {
throw MSSQLCoreError.connectionFailed(error.localizedDescription)
}
guard let proc = opened else {
throw openFailure()
guard let proc = opened.proc else {
throw openFailure(detail: opened.refusal)
}
return proc
}
Expand All @@ -373,14 +378,16 @@ nonisolated final class FreeTDSConnection: @unchecked Sendable {
}
}

// A refused login's reason lands in process-wide state the next login clears, so it is read under the same lock.
private func open(
_ login: UnsafeMutablePointer<LOGINREC>,
serverName: String,
deadline: MSSQLConnectDeadline
) throws -> UnsafeMutablePointer<DBPROCESS>? {
) throws -> (proc: UnsafeMutablePointer<DBPROCESS>?, refusal: String) {
Self.loginStartLock.lock()
defer { Self.loginStartLock.unlock() }
return try withKerberosEnvironmentIfNeeded(deadline: deadline) {
freetdsClearError(for: nil)
let proc = try withKerberosEnvironmentIfNeeded(deadline: deadline) {
let timeoutMilliseconds = deadline.remainingMilliseconds
guard timeoutMilliseconds > 0 else {
throw MSSQLCoreError.connectionTimedOut(isKerberos: options.authMethod == .windows)
Expand All @@ -389,6 +396,7 @@ nonisolated final class FreeTDSConnection: @unchecked Sendable {
_ = dbsetlogintime(seconds)
return dbopen(login, serverName)
}
return (proc, proc == nil ? freetdsGetError(for: nil) : "")
}

private func discardKerberosCache() {
Expand Down Expand Up @@ -426,8 +434,7 @@ nonisolated final class FreeTDSConnection: @unchecked Sendable {
}
}

private func openFailure() -> MSSQLCoreError {
let detail = freetdsGetError(for: nil)
private func openFailure(detail: String) -> MSSQLCoreError {
let msg = detail.isEmpty ? "Check host, port, credentials, and TLS settings" : detail
if let kind = MSSQLTLSClassifier.classifySSLError(detail) {
return .tlsHandshakeFailed(kind: kind, serverMessage: detail)
Expand Down
2 changes: 2 additions & 0 deletions apple/TablePro/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,8 @@ class AppDelegate: NSObject, NSApplicationDelegate {
await AppModuleTermination.stopModuleWork()
await MCPServerManager.shared.stop()
await DatabaseManager.shared.runPostDisconnectScriptsBeforeQuit()
// A Vault lease outlives the app on the server until its TTL, so its database user goes now.
await VaultDatabaseCredentials.shared.revokeAllLeases()
NSApp.reply(toApplicationShouldTerminate: true)
}
return .terminateLater
Expand Down
50 changes: 34 additions & 16 deletions apple/TablePro/Core/Database/ConnectionCredentialResolver.swift
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,14 @@ enum ConnectionCredentialResolver {
}

// A nil username keeps the connection's own; Redshift IAM and a Vault database role hand back another.
// A sign-in that carries a lease belongs to whoever uses it, which releases it when done.
// A sign-in that carries a lease belongs to whoever uses it, which releases it when done. `leaseOwner` replaces
// `credentialOwner(for:)`, for a Vault user that must not be shared.
static func resolveSignIn(
for connection: DatabaseConnection,
fields: [String: String],
override: String? = nil,
deadline: ConnectionDeadline? = nil
deadline: ConnectionDeadline? = nil,
leaseOwner: UUID? = nil
) async throws -> ResolvedSignIn {
if let minter = iamPasswordMinter(for: connection, fields: fields) {
return try await minter.mint(deadline: deadline)
Expand All @@ -43,7 +45,11 @@ enum ConnectionCredentialResolver {
if KerberosAuthFields.isSelected(in: connection.additionalFields) {
return ResolvedSignIn(username: nil, password: "")
}
return try await resolveStoredSignIn(for: connection, override: override)
return try await resolveStoredSignIn(
for: connection,
override: override,
leaseOwner: leaseOwner ?? credentialOwner(for: connection)
)
}

// A lease is a database user Vault creates, so a caller that only wants to know whether a password exists asks this.
Expand All @@ -60,27 +66,40 @@ enum ConnectionCredentialResolver {
return connection.passwordSource
}

private static func resolveStoredSignIn(for connection: DatabaseConnection, override: String?) async throws -> ResolvedSignIn {
private static func resolveStoredSignIn(
for connection: DatabaseConnection,
override: String?,
leaseOwner: UUID
) async throws -> ResolvedSignIn {
if let override { return ResolvedSignIn(username: nil, password: override) }
if case .profile(let profileId) = connection.credentialMode,
let profile = CredentialProfileStorage.shared.profile(for: profileId) {
return try await resolveProfileSignIn(profile, for: connection)
return try await resolveProfileSignIn(profile, for: connection, leaseOwner: leaseOwner)
}
if let passwordSource = connection.passwordSource {
guard ConnectionStorage.shared.storeIsTrusted else {
throw PasswordSourceResolver.ResolutionError.storeNotTrusted
}
return try await resolveSource(passwordSource, for: connection)
return try await resolveSource(passwordSource, for: connection, leaseOwner: leaseOwner)
}
if connection.usePgpass, readsPgpass(connection) {
return ResolvedSignIn(username: nil, password: pgpassPassword(for: connection, username: resolveUsername(for: connection)))
}
return ResolvedSignIn(username: nil, password: ConnectionStorage.shared.loadPassword(for: connection.id) ?? "")
}

private static func resolveSource(_ source: PasswordSource, for connection: DatabaseConnection) async throws -> ResolvedSignIn {
private static func resolveSource(
_ source: PasswordSource,
for connection: DatabaseConnection,
leaseOwner: UUID
) async throws -> ResolvedSignIn {
if case .vaultDatabaseRole(let role) = source {
return try await VaultDatabaseCredentials.shared.signIn(role, interactive: false)
return try await VaultDatabaseCredentials.shared.signIn(
role,
owner: leaseOwner,
for: connection.id,
interactive: false
)
}
let password = try await PasswordSourceResolver.resolve(source, for: ConnectionScriptContext(connection: connection))
return ResolvedSignIn(username: nil, password: password)
Expand All @@ -99,10 +118,8 @@ enum ConnectionCredentialResolver {
return profile.username
}

/// Which record a prompted password is remembered against. A profile answers for every
/// connection linked to it, so one profile in "ask every time" mode asks once per launch
/// rather than once per connection.
static func promptCacheKey(for connection: DatabaseConnection) -> UUID {
// A profile answers for every connection linked to it: one prompt per launch, one Vault user while its lease lives.
static func credentialOwner(for connection: DatabaseConnection) -> UUID {
connection.credentialMode.profileId ?? connection.id
}

Expand All @@ -125,7 +142,8 @@ enum ConnectionCredentialResolver {

private static func resolveProfileSignIn(
_ profile: CredentialProfile,
for connection: DatabaseConnection
for connection: DatabaseConnection,
leaseOwner: UUID
) async throws -> ResolvedSignIn {
switch profile.passwordMode {
case .stored:
Expand All @@ -141,7 +159,7 @@ enum ConnectionCredentialResolver {
guard CredentialProfileStorage.shared.storeIsTrusted else {
throw PasswordSourceResolver.ResolutionError.profileStoreNotTrusted
}
return try await resolveSource(source, for: connection)
return try await resolveSource(source, for: connection, leaseOwner: leaseOwner)
}
}

Expand Down Expand Up @@ -214,9 +232,9 @@ enum ConnectionCredentialResolver {
struct ResolvedSignIn: Equatable, Sendable {
let username: String?
let password: String
let lease: VaultLease?
let lease: VaultLeaseHold?

init(username: String?, password: String, lease: VaultLease? = nil) {
init(username: String?, password: String, lease: VaultLeaseHold? = nil) {
self.username = username
self.password = password
self.lease = lease
Expand Down
36 changes: 11 additions & 25 deletions apple/TablePro/Core/Database/DatabaseManager+Health.swift
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,16 @@ extension DatabaseManager {
|| error is LocalCredentialConsentError {
return .stop(ConnectionFailureClassifier.info(for: error))
}
guard isAuthenticationFailure(error) else { return .retry(nil) }
// The lease renewal stops on the same Vault errors; an unreachable or failing Vault is worth another try.
if error is VaultError || error is VaultRequestError {
let info = ConnectionFailureClassifier.info(for: error)
return VaultLease.isDefinitive(error) ? .stop(info) : .retry(info)
}
// The new user is kept, and the next attempt may find it loaded.
if error is VaultUserNotLoaded {
return .retry(ConnectionFailureClassifier.info(for: error))
}
guard ConnectionFailureClassifier.isAuthenticationFailure(error) else { return .retry(nil) }
let message = String(format: String(localized: "Reconnect failed: %@"), error.localizedDescription)
return .stop(ConnectionFailureInfo(message: message))
}
Expand Down Expand Up @@ -631,7 +640,7 @@ extension DatabaseManager {
guard allowsCredentialPrompt else { return .fail }
guard ConnectionCredentialResolver.promptsForPassword(session.connection),
!pluginManager.hidesPassword(for: session.connection),
isAuthenticationFailure(error)
ConnectionFailureClassifier.isAuthenticationFailure(error)
else {
return .fail
}
Expand All @@ -652,29 +661,6 @@ extension DatabaseManager {
return .retry(prompted)
}

private static let invalidAuthorizationSQLState = "28000"
private static let mysqlAccessDeniedErrorCode = 1_045

internal func isAuthenticationFailure(_ error: Error) -> Bool {
if let pluginError = error as? any PluginDriverError {
if pluginError.pluginSqlState == Self.invalidAuthorizationSQLState {
return true
}
if pluginError.pluginErrorCode == Self.mysqlAccessDeniedErrorCode {
return true
}
return messageIndicatesAuthenticationFailure(pluginError.pluginErrorMessage)
}
return messageIndicatesAuthenticationFailure(error.localizedDescription)
}

private func messageIndicatesAuthenticationFailure(_ message: String) -> Bool {
let lowered = message.lowercased()
return lowered.contains("access denied")
|| lowered.contains("authentication failed")
|| lowered.contains("invalid credentials")
}

// A superseded attempt leaves the slot alone: the tunnel under this connection's id is the newer attempt's.
private func closeReconnectTunnels(for connection: DatabaseConnection, ownsAttempt: () -> Bool) async {
guard ownsAttempt(), let tunnelManager = activeTunnelManager(for: connection) else { return }
Expand Down
7 changes: 7 additions & 0 deletions apple/TablePro/Core/Database/DatabaseManager+Queries.swift
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,13 @@ extension DatabaseManager {
}

let tunnelManager = activeTunnelManager(for: connection)
// The form tests under a throwaway id, so a role of the connection's own leases a user no connect reuses.
defer {
let owner = ConnectionCredentialResolver.credentialOwner(for: connection)
if owner == connection.id, activeSessions[connection.id] == nil {
VaultDatabaseCredentials.shared.endUse(connection: connection.id, live: Set(activeSessions.keys))
}
}

let result: ConnectionTestResult
do {
Expand Down
3 changes: 2 additions & 1 deletion apple/TablePro/Core/Database/DatabaseManager+Sessions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -245,7 +245,7 @@ extension DatabaseManager {
static func promptCacheKey(for connection: DatabaseConnection) -> PromptedPasswordKey {
let sharedByProfile = connection.credentialMode.profileId != nil
return PromptedPasswordKey(
owner: ConnectionCredentialResolver.promptCacheKey(for: connection),
owner: ConnectionCredentialResolver.credentialOwner(for: connection),
destination: sharedByProfile ? "" : connection.destination.digest
)
}
Expand Down Expand Up @@ -833,6 +833,7 @@ extension DatabaseManager {
"[close] disconnectSession driver.disconnect done connId=\(sessionId, privacy: .public) elapsedMs=\(Int(Date().timeIntervalSince(driverStart) * 1_000))"
)
removeSessionEntry(for: sessionId)
VaultDatabaseCredentials.shared.endUse(connection: sessionId, live: Set(activeSessions.keys))

await SchemaService.shared.invalidate(connectionId: sessionId)
await DatabaseTreeMetadataService.shared.handleDisconnect(connectionId: sessionId)
Expand Down
1 change: 1 addition & 0 deletions apple/TablePro/Core/Database/DatabaseManager+Tunnel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ extension DatabaseManager {
type: connection.type,
sshConfig: SSHConfiguration(),
sslConfig: tunnelSSL,
credentialMode: connection.credentialMode,
passwordSource: connection.passwordSource,
additionalFields: effectiveFields
)
Expand Down
16 changes: 13 additions & 3 deletions apple/TablePro/Core/Database/NativeDumpService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,8 @@ final class NativeDumpService: ObservableObject {
private var cancelRequested = false
private var preparation: Task<NativeDumpDescriptor.Request, any Error>?
// The Vault lease the tool signs in with, held until the tool exits.
private var credentialLease: VaultLease?
private var credentialLease: VaultLeaseHold?
private var endsCredentialLease = false
// The roots file the tool checks the server with, removed when the tool exits.
private var systemTrustAnchors: SystemTrustAnchorFile?
private let runningWork: RunningWorkRegistry
Expand Down Expand Up @@ -397,11 +398,15 @@ final class NativeDumpService: ObservableObject {

var effective = session?.effectiveConnection ?? connection
let resolvedFields = DatabaseDriverFactory.resolvedAdditionalFields(for: effective) ?? effective.additionalFields
// A password on the tool's command line is readable while it runs, so that Vault user is the tool's alone and
// is revoked when it exits.
let exposesPassword = descriptor.exposesPasswordInArguments
// The connect's own resolution, errors included: a Keychain read misses every other source.
let signIn = try await ConnectionCredentialResolver.resolveSignIn(
for: effective,
fields: resolvedFields,
override: session?.cachedPassword
override: session?.cachedPassword,
leaseOwner: exposesPassword ? UUID() : nil
)
// A tool signs in with the Keychain secrets the driver gets beside the password.
if let token = resolvedFields[ConnectionSecretOptions.mongoSessionTokenFieldId], !token.isEmpty {
Expand All @@ -416,6 +421,7 @@ final class NativeDumpService: ObservableObject {
let password = signIn.password
releaseRunResources()
credentialLease = signIn.lease
endsCredentialLease = exposesPassword
signIn.lease?.start { _ in }
var jobStarted = false
defer {
Expand Down Expand Up @@ -479,7 +485,11 @@ final class NativeDumpService: ObservableObject {
}

private func releaseRunResources() {
credentialLease?.release()
if endsCredentialLease {
credentialLease?.end()
} else {
credentialLease?.release()
}
credentialLease = nil
systemTrustAnchors?.remove()
systemTrustAnchors = nil
Expand Down
4 changes: 2 additions & 2 deletions apple/TablePro/Core/Database/Vault/VaultAuthenticator.swift
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ actor VaultAuthenticator {
do {
grant = try await VaultClient(endpoint: endpoint, transport: transport).lookupSelf(token: value)
} catch let error as VaultRequestError {
throw VaultError.tokenRejected(source, error.message)
throw VaultError.signInFailure(error, at: endpoint, otherwise: .tokenRejected(source, error.message))
}
// The user owns this token, so it is never renewed here.
return VaultToken(
Expand All @@ -176,7 +176,7 @@ actor VaultAuthenticator {
grant = try await VaultClient(endpoint: endpoint, transport: transport)
.appRoleLogin(mount: mount, roleId: roleId, secretId: secretId)
} catch let error as VaultRequestError {
throw VaultError.tokenRejected(.appRole, error.message)
throw VaultError.signInFailure(error, at: endpoint, otherwise: .tokenRejected(.appRole, error.message))
}
return token(from: grant, source: .appRole)
}
Expand Down
3 changes: 3 additions & 0 deletions apple/TablePro/Core/Database/Vault/VaultClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,9 @@ struct VaultRequestError: Error, Equatable {

var isPermissionDenied: Bool { status == 403 }

// Rate limited, sealed, or a proxy in front of it that cannot reach it: the same request can work in a moment.
var isTransient: Bool { [429, 502, 503, 504].contains(status) }

// Vault wraps several causes as "2 errors occurred:\n\t* permission denied\n\t* invalid token".
var message: String {
let lines = messages.flatMap { $0.components(separatedBy: .newlines) }
Expand Down
Loading
Loading