Merge pull request #585 from groue/dev/issue-583

Fix use of SQLite authorizers
This commit is contained in:
Gwendal Roué authored and GitHub committed 2019-08-03 13:37:50 +02:00
commit 8d5cddd293
10 files changed
+249 -122

No files matched your search

+1
View File
@@ -61,6 +61,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one expection:
- [#574](https://github.com/groue/GRDB.swift/pull/574): SwiftLint
- [#576](https://github.com/groue/GRDB.swift/pull/576): Expose table name and full-text filtering methods to DerivableRequest
- [#577](https://github.com/groue/GRDB.swift/pull/577): Rename `aliased(_:)` methods to `forKey(_:)`
- [#585](https://github.com/groue/GRDB.swift/pull/585): Fix use of SQLite authorizers
### API Diff
+4 -4
View File
@@ -1233,8 +1233,8 @@
56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloatTests.swift; sourceTree = "<group>"; };
56B7F4391BEB42D500E39BBF /* Migration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Migration.swift; sourceTree = "<group>"; };
56B86E72220FF4E000524C16 /* SQLLiteralTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLLiteralTests.swift; sourceTree = "<group>"; };
56B8C2401CA1758F00510325 /* Realm.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Realm.framework; path = "Realm/build/osx/swift-10.2.1/Realm.framework"; sourceTree = "<group>"; };
56B8C2411CA1758F00510325 /* RealmSwift.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = RealmSwift.framework; path = "Realm/build/osx/swift-10.2.1/RealmSwift.framework"; sourceTree = "<group>"; };
56B8C2401CA1758F00510325 /* Realm.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Realm.framework; path = "Realm/build/osx/swift-10.3/Realm.framework"; sourceTree = "<group>"; };
56B8C2411CA1758F00510325 /* RealmSwift.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = RealmSwift.framework; path = "Realm/build/osx/swift-10.3/RealmSwift.framework"; sourceTree = "<group>"; };
56B8F49A1B4E2F3600C24296 /* GRDB.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = GRDB.xcconfig; sourceTree = "<group>"; };
56B9649C1DA51B4C0002DA19 /* FTS5.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5.swift; sourceTree = "<group>"; };
56B964B01DA51D010002DA19 /* FTS5TokenizerDescriptor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5TokenizerDescriptor.swift; sourceTree = "<group>"; };
@@ -3538,7 +3538,7 @@
DEBUG_INFORMATION_FORMAT = dwarf;
FRAMEWORK_SEARCH_PATHS = (
"$(inherited)",
"$(PROJECT_DIR)/Tests/Performance/Realm/build/osx/swift-10.2.1",
"$(PROJECT_DIR)/Tests/Performance/Realm/build/osx/swift-10.3",
);
GCC_NO_COMMON_BLOCKS = YES;
INFOPLIST_FILE = Tests/Info.plist;
@@ -3561,7 +3561,7 @@
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
FRAMEWORK_SEARCH_PATHS = (
"$(inherited)",
"$(PROJECT_DIR)/Tests/Performance/Realm/build/osx/swift-10.2.1",
"$(PROJECT_DIR)/Tests/Performance/Realm/build/osx/swift-10.3",
);
GCC_NO_COMMON_BLOCKS = YES;
INFOPLIST_FILE = Tests/Info.plist;
+58 -16
View File
@@ -36,7 +36,7 @@ extension Database {
/// - returns: A SelectStatement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
func makeSelectStatement(sql: String, prepFlags: Int32) throws -> SelectStatement {
return try SelectStatement.prepare(sql: sql, prepFlags: prepFlags, in: self)
return try SelectStatement.prepare(self, sql: sql, prepFlags: prepFlags)
}
/// Returns a prepared statement that can be reused.
@@ -85,7 +85,7 @@ extension Database {
/// - returns: An UpdateStatement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
func makeUpdateStatement(sql: String, prepFlags: Int32) throws -> UpdateStatement {
return try UpdateStatement.prepare(sql: sql, prepFlags: prepFlags, in: self)
return try UpdateStatement.prepare(self, sql: sql, prepFlags: prepFlags)
}
/// Returns a prepared statement that can be reused.
@@ -180,16 +180,15 @@ extension Database {
// Compile
do {
let statementCompilationAuthorizer = StatementCompilationAuthorizer()
authorizer = statementCompilationAuthorizer
defer { authorizer = nil }
nextStatement = try UpdateStatement(
database: self,
statementStart: statementStart,
statementEnd: &statementEnd,
prepFlags: 0,
authorizer: statementCompilationAuthorizer)
let authorizer = StatementCompilationAuthorizer()
nextStatement = try withAuthorizer(authorizer) {
try UpdateStatement(
database: self,
statementStart: statementStart,
statementEnd: &statementEnd,
prepFlags: 0,
authorizer: authorizer)
}
}
guard let statement = nextStatement else {
@@ -222,11 +221,54 @@ extension Database {
extension Database {
func updateStatementWillExecute(_ statement: UpdateStatement) {
observationBroker.updateStatementWillExecute(statement)
func executeUpdateStatement(_ statement: UpdateStatement) throws {
let authorizer = observationBroker.updateStatementWillExecute(statement)
let sqliteStatement = statement.sqliteStatement
var code: Int32 = SQLITE_OK
withAuthorizer(authorizer) {
while true {
code = sqlite3_step(sqliteStatement)
if code == SQLITE_ROW {
// Statement returns a row, but the user ignores the
// content of this row:
//
// try db.execute(sql: "SELECT ...")
//
// That's OK: maybe the selected rows perform side effects.
// For example:
//
// try db.execute(sql: "SELECT sqlcipher_export(...)")
//
// Or maybe the user doesn't know that the executed statement
// return rows (https://github.com/groue/GRDB.swift/issues/15);
//
// try db.execute(sql: "PRAGMA journal_mode=WAL")
//
// It is thus important that we consume *all* rows.
continue
} else {
break
}
}
}
// Statement has been fully executed, and authorizer has been reset.
// We can now move on further tasks.
if code == SQLITE_DONE {
try updateStatementDidExecute(statement)
} else {
assert(code != SQLITE_ROW)
try updateStatementDidFail(statement)
throw DatabaseError(
resultCode: code,
message: lastErrorMessage,
sql: statement.sql,
arguments: statement.arguments)
}
}
func updateStatementDidExecute(_ statement: UpdateStatement) throws {
private func updateStatementDidExecute(_ statement: UpdateStatement) throws {
if statement.invalidatesDatabaseSchemaCache {
clearSchemaCache()
}
@@ -234,7 +276,7 @@ extension Database {
try observationBroker.updateStatementDidExecute(statement)
}
func updateStatementDidFail(_ statement: UpdateStatement) throws {
private func updateStatementDidFail(_ statement: UpdateStatement) throws {
// Failed statements can not be reused, because sqlite3_reset won't
// be able to restore the statement to its initial state:
// https://www.sqlite.org/c3ref/reset.html
+39 -21
View File
@@ -129,27 +129,8 @@ public final class Database {
var lastErrorCode: ResultCode { return ResultCode(rawValue: sqlite3_errcode(sqliteConnection)) }
var lastErrorMessage: String? { return String(cString: sqlite3_errmsg(sqliteConnection)) }
// Statement authorizer
var authorizer: StatementAuthorizer? {
didSet {
switch (oldValue, authorizer) {
case (.some, nil):
sqlite3_set_authorizer(sqliteConnection, nil, nil)
case (nil, .some):
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_set_authorizer(
sqliteConnection,
{ (dbPointer, actionCode, cString1, cString2, cString3, cString4) -> Int32 in
guard let dbPointer = dbPointer else { return SQLITE_OK }
let db = Unmanaged<Database>.fromOpaque(dbPointer).takeUnretainedValue()
return db.authorizer!.authorize(actionCode, cString1, cString2, cString3, cString4)
},
dbPointer)
default:
break
}
}
}
// Statement authorizer. Use withAuthorizer(_:_:).
fileprivate var _authorizer: StatementAuthorizer? //
// Transaction observers management
lazy var observationBroker = DatabaseObservationBroker(self)
@@ -221,6 +202,7 @@ extension Database {
setupBusyMode()
setupDefaultFunctions()
setupDefaultCollations()
setupAuthorizer()
observationBroker.installCommitAndRollbackHooks()
try activateExtendedCodes()
@@ -352,6 +334,29 @@ extension Database {
add(collation: .localizedStandardCompare)
}
private func setupAuthorizer() {
// SQLite authorizer is set only once per database connection.
//
// This is because authorizer changes have SQLite invalidate statements,
// with undesired side effects. See:
//
// - DatabaseCursorTests.testIssue583()
// - http://sqlite.1065341.n5.nabble.com/Issue-report-sqlite3-set-authorizer-triggers-error-4-516-SQLITE-ABORT-ROLLBACK-during-statement-itern-td107972.html
// swiftlint:disable:previous line_length
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_set_authorizer(
sqliteConnection,
{ (dbPointer, actionCode, cString1, cString2, cString3, cString4) -> Int32 in
let db = Unmanaged<Database>.fromOpaque(dbPointer.unsafelyUnwrapped).takeUnretainedValue()
guard let authorizer = db._authorizer else {
return SQLITE_OK
}
return authorizer.authorize(actionCode, cString1, cString2, cString3, cString4)
},
dbPointer)
}
private func activateExtendedCodes() throws {
let code = sqlite3_extended_result_codes(sqliteConnection, 1)
guard code == SQLITE_OK else {
@@ -598,6 +603,19 @@ extension Database {
}
}
extension Database {
// MARK: - Authorizer
func withAuthorizer<T>(_ authorizer: StatementAuthorizer?, _ block: () throws -> T) rethrows -> T {
SchedulingWatchdog.preconditionValidQueue(self)
let old = self._authorizer
self._authorizer = authorizer
defer { self._authorizer = old }
return try block()
}
}
extension Database {
// MARK: - Transactions & Savepoint
+38 -73
View File
@@ -43,6 +43,7 @@ public class Statement {
/// statement in the C string.
/// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from
/// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html)
/// - parameter authorizer: A StatementCompilationAuthorizer
/// - throws: DatabaseError in case of compilation error.
required init?(
database: Database,
@@ -224,46 +225,41 @@ public class Statement {
// MARK: - Statement Preparation
/// A common protocol for UpdateStatement and SelectStatement, only used as
/// support for SelectStatement.prepare(...) and UpdateStatement.prepare(...).
protocol StatementProtocol { }
extension Statement: StatementProtocol { }
extension StatementProtocol where Self: Statement {
extension Statement {
// Static method instead of an initializer because initializer can't run
// inside `sqlCodeUnits.withUnsafeBufferPointer`.
static func prepare(sql: String, prepFlags: Int32, in database: Database) throws -> Self {
static func prepare(_ db: Database, sql: String, prepFlags: Int32) throws -> Self {
let authorizer = StatementCompilationAuthorizer()
database.authorizer = authorizer
defer { database.authorizer = nil }
return try sql.utf8CString.withUnsafeBufferPointer { buffer in
let statementStart = buffer.baseAddress!
var statementEnd: UnsafePointer<Int8>? = nil
guard let statement = try self.init(
database: database,
statementStart: statementStart,
statementEnd: &statementEnd,
prepFlags: prepFlags,
authorizer: authorizer) else
{
throw DatabaseError(
resultCode: .SQLITE_ERROR,
message: "empty statement",
sql: sql)
return try db.withAuthorizer(authorizer) {
try sql.utf8CString.withUnsafeBufferPointer { buffer in
let statementStart = buffer.baseAddress!
var statementEnd: UnsafePointer<Int8>? = nil
guard let statement = try self.init(
database: db,
statementStart: statementStart,
statementEnd: &statementEnd,
prepFlags: prepFlags,
authorizer: authorizer) else
{
throw DatabaseError(
resultCode: .SQLITE_ERROR,
message: "empty statement",
sql: sql)
}
let remainingSQL = String(cString: statementEnd!).trimmingCharacters(in: .sqlStatementSeparators)
guard remainingSQL.isEmpty else {
throw DatabaseError(
resultCode: .SQLITE_MISUSE,
message: """
Multiple statements found. To execute multiple statements, \
use Database.execute(sql:) instead.
""",
sql: sql)
}
return statement
}
let remainingSQL = String(cString: statementEnd!).trimmingCharacters(in: .sqlStatementSeparators)
guard remainingSQL.isEmpty else {
throw DatabaseError(
resultCode: .SQLITE_MISUSE,
message: """
Multiple statements found. To execute multiple statements, \
use Database.execute(sql:) instead.
""",
sql: sql)
}
return statement
}
}
}
@@ -293,7 +289,7 @@ public final class SelectStatement: Statement {
/// statement in the C string.
/// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from
/// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html)
/// - authorizer: A StatementCompilationAuthorizer
/// - parameter authorizer: A StatementCompilationAuthorizer
/// - throws: DatabaseError in case of compilation error.
required init?(
database: Database,
@@ -456,7 +452,7 @@ public final class UpdateStatement: Statement {
/// statement in the C string.
/// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from
/// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html)
/// - authorizer: A StatementCompilationAuthorizer
/// - parameter authorizer: A StatementCompilationAuthorizer
/// - throws: DatabaseError in case of compilation error.
required init?(
database: Database,
@@ -484,42 +480,11 @@ public final class UpdateStatement: Statement {
SchedulingWatchdog.preconditionValidQueue(database)
prepare(withArguments: arguments)
try reset()
database.updateStatementWillExecute(self)
while true {
switch sqlite3_step(sqliteStatement) {
case SQLITE_ROW:
// The statement did return a row, and the user ignores the
// content of this row:
//
// try db.execute(sql: "SELECT ...")
//
// That's OK: maybe the selected rows perform side effects.
// For example:
//
// try db.execute(sql: "SELECT sqlcipher_export(...)")
//
// Or maybe the user doesn't know that the executed statement
// return rows (https://github.com/groue/GRDB.swift/issues/15);
//
// try db.execute(sql: "PRAGMA journal_mode=WAL")
//
// It is thus important that we consume *all* rows.
continue
case SQLITE_DONE:
try database.updateStatementDidExecute(self)
return
case let code:
try database.updateStatementDidFail(self)
throw DatabaseError(
resultCode: code,
message: database.lastErrorMessage,
sql: sql,
arguments: self.arguments) // Error uses self.arguments, not the optional arguments parameter.
}
}
// Statement does not know how to execute itself, because it does not
// know how to handle its errors, or if truncate optimisation should be
// prevented or not. Database knows.
try database.executeUpdateStatement(self)
}
}
+6 -5
View File
@@ -206,7 +206,10 @@ class DatabaseObservationBroker {
// MARK: - Statement execution
func updateStatementWillExecute(_ statement: UpdateStatement) {
/// Setups observation of changes that are about to be performed by the
/// statement, and returns the authorizer that should be used during
/// statement execution.
func updateStatementWillExecute(_ statement: UpdateStatement) -> StatementAuthorizer? {
// As statement executes, it may trigger database changes that will
// be notified to transaction observers. As a consequence, observers
// may disable themselves with stopObservingDatabaseChangesUntilNextTransaction()
@@ -285,16 +288,15 @@ class DatabaseObservationBroker {
}
if observesRowDeletion {
database.authorizer = TruncateOptimizationBlocker()
return TruncateOptimizationBlocker()
} else {
database.authorizer = nil
return nil
}
}
func updateStatementDidFail(_ statement: UpdateStatement) throws {
// Undo updateStatementWillExecute
statementObservations = []
database.authorizer = nil
SchedulingWatchdog.current!.databaseObservationBroker = nil
// Reset transactionState before databaseDidRollback eventually
@@ -319,7 +321,6 @@ class DatabaseObservationBroker {
func updateStatementDidExecute(_ statement: UpdateStatement) throws {
// Undo updateStatementWillExecute
statementObservations = []
database.authorizer = nil
SchedulingWatchdog.current!.databaseObservationBroker = nil
// Has statement any effect on transaction/savepoints?
+1 -1
View File
@@ -340,7 +340,7 @@ extension JSONRequiredEncoder: UnkeyedEncodingContainer {
}
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
fileprivate var iso8601Formatter: ISO8601DateFormatter = {
private var iso8601Formatter: ISO8601DateFormatter = {
let formatter = ISO8601DateFormatter()
formatter.formatOptions = .withInternetDateTime
return formatter
+1 -1
View File
@@ -408,7 +408,7 @@ private struct MissingColumnError: Error {
}
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
fileprivate var iso8601Formatter: ISO8601DateFormatter = {
private var iso8601Formatter: ISO8601DateFormatter = {
let formatter = ISO8601DateFormatter()
formatter.formatOptions = .withInternetDateTime
return formatter
+1 -1
View File
@@ -330,7 +330,7 @@ Tests/Performance/Realm/build/osx/swift-10.2.1/RealmSwift.framework:
FMDB: Tests/Performance/fmdb/src/fmdb/FMDatabase.h
# Makes sure the Tests/Performance/fmdb submodule has been downloaded
Tests/Performance/fmdb/FMDatabase.h:
Tests/Performance/fmdb/src/fmdb/FMDatabase.h:
$(GIT) submodule update --init Tests/Performance/fmdb
SQLite.swift: Tests/Performance/SQLite.swift/SQLite.xcodeproj
+100
View File
@@ -70,4 +70,104 @@ class DatabaseCursorTests: GRDBTestCase {
}
}
}
// Regression test for http://github.com/groue/GRDB.swift/issues/583
func testIssue583() throws {
struct User: Codable, TableRecord, FetchableRecord, MutablePersistableRecord {
static let databaseTableName: String = "user"
var id: Int64?
var username: String
var isFlagged: Bool
init(id: Int64? = nil, username: String, isFlagged: Bool = false) {
self.id = id
self.username = username
self.isFlagged = isFlagged
}
mutating func didInsert(with rowID: Int64, for column: String?) {
id = rowID
}
}
struct FlagUser: Codable, TableRecord, FetchableRecord, MutablePersistableRecord {
static let databaseTableName: String = "flagUser"
var username: String
}
let queue = try makeDatabaseQueue()
try queue.write { database in
try database.create(table: User.databaseTableName) { definition in
definition.column("id", .integer).primaryKey(autoincrement: true)
definition.column("username", .text).notNull()
definition.column("isFlagged", .boolean).notNull().defaults(to: false)
}
try database.create(table: FlagUser.databaseTableName) { definition in
definition.column("username", .text).notNull()
}
try [Int](0...50).forEach {
var user = User(username: "User\($0)")
try user.insert(database)
}
try [Int](40...60).forEach {
var flag = FlagUser(username: "User\($0)")
try flag.insert(database)
}
}
let query = "SELECT * FROM flagUser WHERE (SELECT COUNT(id) FROM user WHERE username = flagUser.username AND isFlagged = 1) = 0"
try queue.inDatabase { database in
let cursor = try FlagUser.fetchCursor(database, sql: query)
while let flagged = try cursor.next() {
_ = try User.fetchOne(database, sql: "SELECT * FROM user WHERE username = '\(flagged.username)' LIMIT 1") ??
User(username: flagged.username)
}
}
// For the record, the lines below show how this test used to fail,
// with raw C SQLite3 apis. The faulty line is the call to
// sqlite3_set_authorizer during the statement iteration.
// if #available(OSX 10.14, *) {
// var connection: SQLiteConnection? = nil
// sqlite3_open_v2(":memory:", &connection, SQLITE_OPEN_READWRITE | SQLITE_OPEN_NOMUTEX, nil)
// sqlite3_extended_result_codes(connection, 1)
//
// sqlite3_exec(connection, """
// CREATE TABLE user (username TEXT NOT NULL);
// CREATE TABLE flagUser (username TEXT NOT NULL);
// INSERT INTO flagUser (username) VALUES ('User1');
// INSERT INTO flagUser (username) VALUES ('User2');
// """, nil, nil, nil)
//
// var statement: SQLiteStatement? = nil
// sqlite3_set_authorizer(connection, { (_, _, _, _, _, _) in SQLITE_OK }, nil)
// sqlite3_prepare_v3(connection, """
// SELECT * FROM flagUser WHERE (SELECT COUNT(*) FROM user WHERE username = flagUser.username) = 0
// """, -1, 0, &statement, nil)
// sqlite3_set_authorizer(connection, nil, nil)
// while true {
// let code = sqlite3_step(statement)
// if code == SQLITE_DONE {
// break
// } else if code == SQLITE_ROW {
// // part of the compilation of another statement, here
// // reduced to the strict minimum that reproduces
// // the error.
// sqlite3_set_authorizer(connection, nil, nil)
// } else {
// print(String(cString: sqlite3_errmsg(connection)))
// XCTFail("Error \(code)")
// break
// }
// }
// sqlite3_finalize(statement)
// sqlite3_close_v2(connection)
// }
}
}