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
47 changes: 18 additions & 29 deletions apple/TablePro/Core/Database/LocalCredentialConsent.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ internal struct LocalCredentialQuestion: Equatable, Sendable {
let uses: [String]
let destination: String
let origin: ConnectionOrigin
// The destination is a database file this Mac opens, which the prompt names as a file rather than a server.
var opensFile = false
// Something beyond files: a credential, an SSH key or agent, a profile.
var signsIn = true
}

internal enum LocalCredentialConsentError: Error, Equatable, Sendable {
Expand Down Expand Up @@ -135,13 +139,19 @@ internal final class LocalCredentialConsent {
internal static func question(for connection: DatabaseConnection, uses: [SharedRowLocalUse] = []) -> LocalCredentialQuestion {
let fields = PluginMetadataRegistry.shared.snapshot(for: connection.type)?
.connection.additionalConnectionFields ?? []
let routed = SSHProfileStorage.shared.refreshingLinkedProfile(connection)
let credentials = ConnectionFieldCatalog.localCredentialUses(in: connection.additionalFields)
let file = routed.localDatabaseFiles.first
// The file the sentence names is not listed again below it.
let listed = uses.filter { $0 != file.map { .file(path: $0) } }
return LocalCredentialQuestion(
connectionName: connection.name,
uses: ConnectionFieldCatalog.localCredentialUses(in: connection.additionalFields).map { use in
describe(use, fields: fields)
} + uses.map(describe),
destination: SSHProfileStorage.shared.refreshingLinkedProfile(connection).destinationSummary,
origin: connection.origin
uses: credentials.map { describe($0, fields: fields) } + listed.map(describe),
destination: routed.destinationSummary,
origin: connection.origin,
opensFile: file != nil,
// A socket or an attachment is a file use too, but only a database file here makes the question about one.
signsIn: file == nil || !credentials.isEmpty || listed.contains { if case .file = $0 { false } else { true } }
)
}

Expand Down Expand Up @@ -300,35 +310,14 @@ extension DatabaseConnection {
// holds are not here; a path from the root or the home folder always is.
@MainActor
private func localFileUses(tunnel: SSHConfiguration) -> [SharedRowLocalUse] {
func local(_ value: String?) -> String? {
guard let path = value?.trimmingCharacters(in: .whitespacesAndNewlines), !path.isEmpty else { return nil }
if path.hasPrefix("/") || path.hasPrefix("~") { return path }
let lowered = path.lowercased()
let remote = path == ":memory:"
|| ["md:", "libsql://", "http://", "https://", "ws://", "wss://"].contains { lowered.hasPrefix($0) }
return remote ? nil : path
}
func inLocalMode(_ modeField: String) -> Bool {
(additionalFields[modeField] ?? "local") == "local"
}
var paths: [String] = []
if PluginManager.shared.connectionMode(for: type) == .fileBased, !tunnel.forwardsRemoteFile,
let path = local(database) {
paths.append(path)
}
if inLocalMode("duckdbMode"), let path = local(additionalFields["duckdbFilePath"]) {
paths.append(path)
}
if inLocalMode("libsqlMode"), let path = local(additionalFields["libsqlFilePath"]) {
paths.append(path)
}
var paths = localDatabaseFiles
let attached = (try? AttachedDatabaseList.decode(additionalFields[AttachedDatabaseList.fieldId])) ?? []
paths += attached.compactMap { local($0.path) }
paths += attached.compactMap { Self.localPath($0.path) }
// A host given as a path is the server's socket, or the folder that holds it; a tunnel never dials one here.
if !tunnel.enabled, host.hasPrefix("/") {
paths.append(host)
}
if let socket = local(localSocketPath) {
if let socket = Self.localPath(localSocketPath) {
paths.append(socket)
}
return paths.map { .file(path: $0) }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,21 +10,44 @@ import Foundation
internal enum LocalCredentialPrompt {
internal static func ask(_ question: LocalCredentialQuestion) async -> ConsentAnswer {
await AlertHelper.askConsent(
title: String(localized: "Sign In with Credentials from This Mac?"),
title: title(for: question),
message: message(for: question),
confirmButton: String(localized: "Sign In"),
confirmButton: question.signsIn ? String(localized: "Sign In") : String(localized: "Open"),
window: NSApp.keyWindow
)
}

// A row that only opens files here signs in nowhere, so it asks about the file.
internal static func title(for question: LocalCredentialQuestion) -> String {
question.signsIn
? String(localized: "Sign In with Credentials from This Mac?")
: String(localized: "Open a Database File on This Mac?")
}

internal static func message(for question: LocalCredentialQuestion) -> String {
let summary = String(
format: String(localized: "Connection “%1$@” signs in to %2$@ with credentials stored on this Mac:"),
LoadableExtensionPrompt.singleLine(question.connectionName),
LoadableExtensionPrompt.singleLine(question.destination)
)
let uses = question.uses.map(LoadableExtensionPrompt.singleLine).joined(separator: "\n")
let warning = String(localized: "Allow this only if you trust where the connection signs in.")
let name = LoadableExtensionPrompt.singleLine(question.connectionName)
let destination = LoadableExtensionPrompt.singleLine(question.destination)
let summary: String
switch (question.opensFile, question.uses.isEmpty) {
case (true, true):
summary = String(format: String(localized: "Connection “%1$@” opens the database file %2$@ on this Mac."), name, destination)
case (true, false):
summary = String(
format: String(localized: "Connection “%1$@” opens the database file %2$@ on this Mac, and uses these from this Mac:"),
name,
destination
)
case (false, _):
summary = String(
format: String(localized: "Connection “%1$@” signs in to %2$@ with credentials stored on this Mac:"),
name,
destination
)
}
let uses = question.uses.isEmpty ? nil : question.uses.map(LoadableExtensionPrompt.singleLine).joined(separator: "\n")
let warning = question.signsIn
? String(localized: "Allow this only if you trust where the connection signs in.")
: String(localized: "Allow this only if you trust the file the connection opens.")
return [summary, uses, originLine(question.origin), warning]
.compactMap { $0 }
.joined(separator: "\n\n")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,48 @@ extension DatabaseConnection {
)
}

// Host and port first, then every other server or project the connection may sign in to, so a prompt never
// hides the real host behind a value the engine ignores, or a server behind "(+N more)". Where plugin fields name
// the server, as DuckDB's Remote fields do, they stand in for Host, which nothing dials.
// A database file this Mac opens for the row: a file engine's database, and DuckDB's and libSQL's file in their
// local mode, on those engines only. MotherDuck's `md:`, a server URL, memory and a file the SSH server holds are not here.
var localDatabaseFiles: [String] {
var paths: [String] = []
if PluginMetadataRegistry.shared.snapshot(for: type)?.connectionMode == .fileBased,
!resolvedSSHConfig.forwardsRemoteFile,
let path = Self.localPath(database) {
paths.append(path)
}
// Only the engine that reads a file field: another engine's row never names one in place of its server.
let fileFields: [(engines: [DatabaseType], file: String, mode: String)] = [
([.duckdb], "duckdbFilePath", "duckdbMode"),
([.libsql, .turso], "libsqlFilePath", "libsqlMode"),
]
for field in fileFields where field.engines.contains(type) && (additionalFields[field.mode] ?? "local") == "local" {
if let path = Self.localPath(additionalFields[field.file]) {
paths.append(path)
}
}
var seen: Set<String> = []
return paths.filter { seen.insert($0).inserted }
}

// A path names a file here unless it is MotherDuck's `md:`, a server URL or memory; one from the root or the home
// folder always does.
static func localPath(_ value: String?) -> String? {
guard let path = value?.trimmingCharacters(in: .whitespacesAndNewlines), !path.isEmpty else { return nil }
if path.hasPrefix("/") || path.hasPrefix("~") { return path }
let lowered = path.lowercased()
let remote = path == ":memory:"
|| ["md:", "libsql://", "http://", "https://", "ws://", "wss://"].contains { lowered.hasPrefix($0) }
return remote ? nil : path
}

// The file a file engine opens; otherwise host and port first, then every other server or project the connection
// may sign in to, so a prompt never hides the real host behind a value the engine ignores, or a server behind
// "(+N more)". Where plugin fields name the server, as DuckDB's Remote fields do, they stand in for Host, which
// nothing dials.
var destinationSummary: String {
if let file = localDatabaseFiles.first {
return file
}
var servers: [String]
if activeServerEndpointFields != nil {
let server = serverEndpoint
Expand Down
12 changes: 12 additions & 0 deletions apple/TablePro/Resources/Localizable.xcstrings
Original file line number Diff line number Diff line change
Expand Up @@ -27216,6 +27216,9 @@
},
"Allow NULL" : {

},
"Allow this only if you trust the file the connection opens." : {

},
"Allow this only if you trust where the connection signs in." : {

Expand Down Expand Up @@ -55288,6 +55291,12 @@
}
}
}
},
"Connection “%1$@” opens the database file %2$@ on this Mac, and uses these from this Mac:" : {

},
"Connection “%1$@” opens the database file %2$@ on this Mac." : {

},
"Connection “%1$@” signs in to %2$@ with credentials stored on this Mac:" : {

Expand Down Expand Up @@ -145339,6 +145348,9 @@
}
}
}
},
"Open a Database File on This Mac?" : {

},
"Open a database to browse its tables." : {
"localizations" : {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -548,13 +548,63 @@ struct LocalCredentialConsentTests {
try await makeConsent().check(file, trigger: .request)
try await makeConsent().check(file, trigger: .background)

#expect(spy.questions.map(\.uses) == [["Database File: /tmp/team-copy.sqlite"]])
let question = try #require(spy.questions.first)
#expect(spy.questions.count == 1)
#expect(question.destination == "/tmp/team-copy.sqlite")
#expect(question.uses.isEmpty)
#expect(question.opensFile && !question.signsIn)
#expect(!makeConsent().requiresApproval(motherDuck))
var socket = DatabaseConnection(name: "PG", host: "/run/postgresql", port: 5_432, type: .postgresql)
socket.origin = .teamLibrary
#expect(socket.sharedRowLocalUses(sshUses: []) == [.file(path: "/run/postgresql")])
}

@Test("A SQLite or DuckDB file row's question opens the file on this Mac, and signs in nowhere")
func fileRowQuestionNamesTheFile() {
var sqlite = DatabaseConnection(name: "Local", host: "localhost", port: 0, database: "/tmp/app.sqlite", type: .sqlite)
sqlite.origin = .teamLibrary
var duckdb = DatabaseConnection(
name: "Sales",
type: .duckdb,
additionalFields: ["duckdbMode": "local", "duckdbFilePath": "/tmp/sales.duckdb"]
)
duckdb.origin = .linkedFolder

for (connection, file) in [(sqlite, "/tmp/app.sqlite"), (duckdb, "/tmp/sales.duckdb")] {
let question = LocalCredentialConsent.question(
for: connection,
uses: connection.sharedRowLocalUses(sshUses: [])
)
let message = LocalCredentialPrompt.message(for: question)

#expect(LocalCredentialPrompt.title(for: question) == "Open a Database File on This Mac?")
#expect(message.hasPrefix("Connection “\(connection.name)” opens the database file \(file) on this Mac."))
#expect(!message.contains("signs in to"))
#expect(!message.contains("localhost:0"))
}
}

@Test("Another engine's file field never stands in for its server, and a socket row is no file question")
func onlyAFileEngineNamesAFile() {
var postgres = DatabaseConnection(
name: "Shop",
host: "pg.attacker.example",
port: 5_432,
type: .postgresql,
additionalFields: ["duckdbFilePath": "/tmp/safe.duckdb"]
)
postgres.origin = .teamLibrary
var socket = DatabaseConnection(name: "PG", host: "/run/postgresql", port: 5_432, type: .postgresql)
socket.origin = .teamLibrary

let socketQuestion = LocalCredentialConsent.question(for: socket, uses: socket.sharedRowLocalUses(sshUses: []))

#expect(postgres.destinationSummary.hasPrefix("pg.attacker.example:5432"))
#expect(postgres.localDatabaseFiles.isEmpty)
#expect(!socketQuestion.opensFile && socketQuestion.signsIn)
#expect(LocalCredentialPrompt.title(for: socketQuestion) == "Sign In with Credentials from This Mac?")
}

@Test("The same tunnel and file on a row of this Mac's own asks nothing")
func ownRowDoesNotAsk() {
var own = teamRow(.privateKey)
Expand Down
19 changes: 19 additions & 0 deletions apple/TableProTests/Core/Database/PromptedPasswordKeyTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,25 @@ struct PromptedPasswordKeyTests {
#expect(!connection.destinationSummary.contains("bastion.example.com"))
}

@Test("A file engine's summary names the file it opens, never a host and port, and MotherDuck stays a server")
func summaryNamesTheFile() {
let sqlite = DatabaseConnection(name: "Local", host: "localhost", port: 0, database: "~/data/app.sqlite", type: .sqlite)
let duckdb = DatabaseConnection(
name: "Sales",
type: .duckdb,
additionalFields: ["duckdbMode": "local", "duckdbFilePath": "/tmp/sales.duckdb"]
)
let motherDuck = DatabaseConnection(
name: "Cloud",
type: .duckdb,
additionalFields: ["duckdbMode": "motherduck", "duckdbFilePath": "md:analytics"]
)

#expect(sqlite.destinationSummary == "~/data/app.sqlite")
#expect(duckdb.destinationSummary == "/tmp/sales.duckdb")
#expect(motherDuck.localDatabaseFiles.isEmpty)
}

@Test("A Snowflake account on another engine is not named")
func snowflakeAccountOnlyForSnowflake() {
let connection = DatabaseConnection(
Expand Down
Loading