diff --git a/GRDB/Core/Configuration.swift b/GRDB/Core/Configuration.swift index 397c9f5e6..aab69a7f2 100644 --- a/GRDB/Core/Configuration.swift +++ b/GRDB/Core/Configuration.swift @@ -102,6 +102,65 @@ public struct Configuration { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) public var observesSuspensionNotifications = false + /// If false (the default), statement arguments are not visible in the + /// description of database errors and trace events, preventing sensitive + /// information from leaking in unexpected places. + /// + /// For example: + /// + /// // Error: sensitive information is not printed when an error occurs: + /// do { + /// let email = "..." // sensitive information + /// let player = try Player.filter(Column("email") == email).fetchOne(db) + /// } catch { + /// print(error) + /// } + /// + /// // Trace: sensitive information is not printed when a statement is traced: + /// db.trace { event in + /// print(event) + /// } + /// let email = "..." // sensitive information + /// let player = try Player.filter(Column("email") == email).fetchOne(db) + /// + /// For debugging purpose, you can set this flag to true, and get more + /// precise database reports. It is not recommended to do so in + /// release builds: + /// + /// var config = Configuration() + /// #if DEBUG + /// config.publicStatementArguments = true + /// #endif + /// + /// // The descriptions of trace events and errors now contain the + /// // sensitive information: + /// db.trace { event in + /// print(event) + /// } + /// do { + /// let email = "..." + /// let player = try Player.filter(Column("email") == email).fetchOne(db) + /// } catch { + /// print(error) + /// } + /// + /// Regardless of this flag, you can explicitly ask to see the + /// statement arguments with the `expandedDescription` property of database + /// errors and trace events: + /// + /// // The expanded descriptions of trace events and errors always + /// // contain the sensitive information: + /// db.trace { event in + /// print(event.expandedDescription) + /// } + /// do { + /// let email = "..." + /// let player = try Player.filter(Column("email") == email).fetchOne(db) + /// } catch let error as DatabaseError { + /// print(error.expandedDescription) + /// } + public var publicStatementArguments = false + // MARK: - Managing SQLite Connections private var setups: [(Database) throws -> Void] = [] diff --git a/GRDB/Core/Database+Statements.swift b/GRDB/Core/Database+Statements.swift index cabe9073e..7a4119528 100644 --- a/GRDB/Core/Database+Statements.swift +++ b/GRDB/Core/Database+Statements.swift @@ -589,7 +589,8 @@ extension Database { resultCode: resultCode, message: lastErrorMessage, sql: statement.sql, - arguments: statement.arguments) + arguments: statement.arguments, + publicStatementArguments: configuration.publicStatementArguments) } } diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index ecc76071f..5e7e41d8b 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -713,7 +713,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib impl: .trace_v2( sqliteStatement: OpaquePointer(sqliteStatement), unexpandedSQL: UnsafePointer(unexpandedSQL.assumingMemoryBound(to: CChar.self)), - sqlite3_expanded_sql: sqlite3_expanded_sql)) + sqlite3_expanded_sql: sqlite3_expanded_sql), + publicStatementArguments: configuration.publicStatementArguments) trace(TraceEvent.statement(statement)) } case SQLITE_TRACE_PROFILE: @@ -722,7 +723,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib impl: .trace_v2( sqliteStatement: OpaquePointer(sqliteStatement), unexpandedSQL: nil, - sqlite3_expanded_sql: sqlite3_expanded_sql)) + sqlite3_expanded_sql: sqlite3_expanded_sql), + publicStatementArguments: configuration.publicStatementArguments) let duration = TimeInterval(durationP.pointee) / 1.0e9 #if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS) @@ -897,7 +899,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib resultCode: .SQLITE_ABORT, message: "Database is suspended", sql: statement.sql, - arguments: statement.arguments) + arguments: statement.arguments, + publicStatementArguments: configuration.publicStatementArguments) } } @@ -930,7 +933,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib resultCode: .SQLITE_ABORT, message: "Transaction was aborted", sql: sql(), - arguments: arguments()) + arguments: arguments(), + publicStatementArguments: configuration.publicStatementArguments) } } @@ -1650,7 +1654,10 @@ extension Database { unexpandedSQL: UnsafePointer?, sqlite3_expanded_sql: @convention(c) (OpaquePointer?) -> UnsafeMutablePointer?) } - let impl: Impl + var impl: Impl + + /// See Configuration.publicStatementArguments + var publicStatementArguments: Bool #if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS) /// The executed SQL, where bound parameters are not expanded. @@ -1724,14 +1731,20 @@ extension Database { /// The format of the event description may change between GRDB releases, /// without notice: don't have your application rely on any specific format. public var description: String { - // TODO: consider including arguments depending on database configuration, - // for easy verbose debugging when the database does not contain sensitive information. switch self { case let .statement(statement): - return statement.sql + if statement.publicStatementArguments { + return statement.expandedSQL + } else { + return statement.sql + } case let .profile(statement: statement, duration: duration): let durationString = String(format: "%.3f", duration) - return "\(durationString)s \(statement.sql)" + if statement.publicStatementArguments { + return "\(durationString)s \(statement.expandedSQL)" + } else { + return "\(durationString)s \(statement.sql)" + } } } diff --git a/GRDB/Core/DatabaseError.swift b/GRDB/Core/DatabaseError.swift index b75bbb555..f1fff6199 100644 --- a/GRDB/Core/DatabaseError.swift +++ b/GRDB/Core/DatabaseError.swift @@ -241,17 +241,46 @@ public struct DatabaseError: Error, CustomStringConvertible, CustomNSError { /// The query arguments that yielded the error (if relevant). public let arguments: StatementArguments? - /// Creates a Database Error + /// See Configuration.publicStatementArguments + var publicStatementArguments: Bool + + /// Creates a DatabaseError. + /// + /// - parameters: + /// - resultCode: A ResultCode (defaults to .SQLITE_ERROR). + /// - message: An eventual error message. If nil, the error message is + /// derived from the result code. + /// - sql: An eventual SQL string. + /// - arguments: Eventual Statement arguments. + /// - publicStatementArguments: If false (the default), statement + /// arguments are not visible in the error's `description` property. public init( resultCode: ResultCode = .SQLITE_ERROR, message: String? = nil, sql: String? = nil, - arguments: StatementArguments? = nil) + arguments: StatementArguments?, + publicStatementArguments: Bool = false) { self.extendedResultCode = resultCode self.message = message ?? resultCode.errorString self.sql = sql self.arguments = arguments + self.publicStatementArguments = publicStatementArguments + } + + /// Creates a DatabaseError. + /// + /// - parameters: + /// - resultCode: A ResultCode (defaults to .SQLITE_ERROR). + /// - message: An eventual error message. If nil, the error message is + /// derived from the result code. + /// - sql: An eventual SQL string. + public init( + resultCode: ResultCode = .SQLITE_ERROR, + message: String? = nil, + sql: String? = nil) + { + self.init(resultCode: resultCode, message: message, sql: sql, arguments: nil, publicStatementArguments: false) } /// Creates a Database Error with a raw CInt result code. @@ -259,10 +288,33 @@ public struct DatabaseError: Error, CustomStringConvertible, CustomNSError { /// This initializer is not public because library user is not supposed to /// be exposed to raw result codes. @usableFromInline - init(resultCode: CInt, message: String? = nil, sql: String? = nil, arguments: StatementArguments? = nil) { - self.init(resultCode: ResultCode(rawValue: resultCode), message: message, sql: sql, arguments: arguments) + init(resultCode: CInt, message: String? = nil, sql: String? = nil) { + self.init( + resultCode: ResultCode(rawValue: resultCode), + message: message, + sql: sql) } + /// Creates a Database Error with a raw CInt result code. + /// + /// This initializer is not public because library user is not supposed to + /// be exposed to raw result codes. + @usableFromInline + init( + resultCode: CInt, + message: String? = nil, + sql: String? = nil, + arguments: StatementArguments?, + publicStatementArguments: Bool) + { + self.init( + resultCode: ResultCode(rawValue: resultCode), + message: message, + sql: sql, + arguments: arguments, + publicStatementArguments: publicStatementArguments) + } + static func noSuchTable(_ tableName: String) -> Self { DatabaseError(message: "no such table: \(tableName)") } @@ -421,8 +473,9 @@ extension DatabaseError { if let sql = sql { description += " - while executing `\(sql)`" } - // TODO: consider including arguments depending on database configuration, - // for easy verbose debugging when the database does not contain sensitive information. + if publicStatementArguments, let arguments = arguments, !arguments.isEmpty { + description += " with arguments \(arguments)" + } return description } diff --git a/Tests/GRDBTests/DatabaseErrorTests.swift b/Tests/GRDBTests/DatabaseErrorTests.swift index 2a9ced44b..50666a5b3 100644 --- a/Tests/GRDBTests/DatabaseErrorTests.swift +++ b/Tests/GRDBTests/DatabaseErrorTests.swift @@ -65,7 +65,7 @@ class DatabaseErrorTests: GRDBTestCase { } } - func testDatabaseErrorThrownByUpdateStatementContainSQLAndArguments() throws { + func testDatabaseErrorThrownByUpdateStatementContainSQLAndNoPrivateArguments() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.execute(sql: "CREATE TABLE persons (id INTEGER PRIMARY KEY)") @@ -121,6 +121,65 @@ class DatabaseErrorTests: GRDBTestCase { } } + func testDatabaseErrorThrownByUpdateStatementContainSQLAndPublicArguments() throws { + // Opt in for public statement arguments + dbConfiguration.publicStatementArguments = true + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.execute(sql: "CREATE TABLE persons (id INTEGER PRIMARY KEY)") + try db.execute(sql: "CREATE TABLE pets (masterId INTEGER NOT NULL REFERENCES persons(id), name TEXT)") + } + + // db.execute(sql, arguments) + try dbQueue.inDatabase { db in + do { + try db.execute(sql: "INSERT INTO pets (masterId, name) VALUES (?, ?)", arguments: [1, "Bobby"]) + XCTFail() + } catch let error as DatabaseError { + XCTAssert(error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY) + XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT) + XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version + XCTAssertEqual(error.sql!, "INSERT INTO pets (masterId, name) VALUES (?, ?)") + XCTAssertEqual(error.description.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)` with arguments [1, \"bobby\"]") + XCTAssertEqual(error.expandedDescription.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)` with arguments [1, \"bobby\"]") + } + } + + // statement.execute(arguments) + try dbQueue.inDatabase { db in + do { + let statement = try db.makeStatement(sql: "INSERT INTO pets (masterId, name) VALUES (?, ?)") + try statement.execute(arguments: [1, "Bobby"]) + XCTFail() + } catch let error as DatabaseError { + XCTAssert(error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY) + XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT) + XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version + XCTAssertEqual(error.sql!, "INSERT INTO pets (masterId, name) VALUES (?, ?)") + XCTAssertEqual(error.description.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)` with arguments [1, \"bobby\"]") + XCTAssertEqual(error.expandedDescription.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)` with arguments [1, \"bobby\"]") + } + } + + // statement.execute() + try dbQueue.inDatabase { db in + do { + let statement = try db.makeStatement(sql: "INSERT INTO pets (masterId, name) VALUES (?, ?)") + statement.arguments = [1, "Bobby"] + try statement.execute() + XCTFail() + } catch let error as DatabaseError { + XCTAssert(error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY) + XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT) + XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version + XCTAssertEqual(error.sql!, "INSERT INTO pets (masterId, name) VALUES (?, ?)") + XCTAssertEqual(error.description.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)` with arguments [1, \"bobby\"]") + XCTAssertEqual(error.expandedDescription.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)` with arguments [1, \"bobby\"]") + } + } + } + func testDatabaseErrorThrownByExecuteMultiStatementContainSQL() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -170,5 +229,4 @@ class DatabaseErrorTests: GRDBTestCase { } } } - } diff --git a/Tests/GRDBTests/DatabaseTraceTests.swift b/Tests/GRDBTests/DatabaseTraceTests.swift index 985192e05..478a7b15e 100644 --- a/Tests/GRDBTests/DatabaseTraceTests.swift +++ b/Tests/GRDBTests/DatabaseTraceTests.swift @@ -145,6 +145,27 @@ class DatabaseTraceTests : GRDBTestCase { } } + func testTraceFromConfigurationWithPublicStatementArguments() throws { + var events: [String] = [] + var configuration = Configuration() + configuration.publicStatementArguments = true + configuration.prepareDatabase { db in + db.trace { event in + events.append("SQL: \(event)") + } + } + let dbQueue = try makeDatabaseQueue(configuration: configuration) + try dbQueue.inDatabase { db in + try db.execute(sql: """ + CREATE table t(a); + INSERT INTO t (a) VALUES (?) + """, arguments: [1]) + XCTAssertEqual(events.suffix(2), [ + "SQL: CREATE table t(a)", + "SQL: INSERT INTO t (a) VALUES (1)"]) + } + } + func testStopTrace() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in