diff --git a/GRDB/Core/Configuration.swift b/GRDB/Core/Configuration.swift index bf4bb9f81..c518f7b39 100644 --- a/GRDB/Core/Configuration.swift +++ b/GRDB/Core/Configuration.swift @@ -24,6 +24,13 @@ public struct Configuration { public var trace: TraceFunction? + // MARK: - Encryption + + #if SQLITE_HAS_CODEC + /// The passphrase for encrypted database + public var passphrase: String? + #endif + // MARK: - File Attributes /// The file attributes that should be applied to the database files (see diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index e7bccdb13..a78a66584 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -66,6 +66,12 @@ public final class Database { throw DatabaseError(code: code, message: String.fromCString(sqlite3_errmsg(sqliteConnection))) } + #if SQLITE_HAS_CODEC + if let passphrase = configuration.passphrase { + try Database.setPassphrase(passphrase, forConnection: sqliteConnection) + } + #endif + self.configuration = configuration self.schemaCache = schemaCache self.sqliteConnection = sqliteConnection @@ -860,60 +866,17 @@ extension DatabaseCollation { // ========================================================================= // MARK: - Encryption +#if SQLITE_HAS_CODEC extension Database { - - /// TODO - class func supportsEncryption() -> Bool { - #if SQLITE_HAS_CODEC - return true - #else - return false - #endif + private class func setPassphrase(passphrase: String, forConnection sqliteConnection: SQLiteConnection) throws { + let data = passphrase.dataUsingEncoding(NSUTF8StringEncoding)! + let code = sqlite3_key(sqliteConnection, data.bytes, Int32(data.length)) + guard code == SQLITE_OK else { + throw DatabaseError(code: code, message: String.fromCString(sqlite3_errmsg(sqliteConnection))) + } } - - /// TODO - public func setKey(passphrase: String) throws { - #if SQLITE_HAS_CODEC - let data = passphrase.dataUsingEncoding(NSUTF8StringEncoding)! - let code = sqlite3_key(sqliteConnection, data.bytes, Int32(data.length)) - guard code == SQLITE_OK else { - throw DatabaseError(code: code, message: String.fromCString(sqlite3_errmsg(sqliteConnection))) - } - -// // https://www.zetetic.net/sqlcipher/sqlcipher-api/#key -// // > When opening an existing database, PRAGMA key will not -// // > immediately throw an error if the key provided is incorrect. -// // > To test that the database can be successfully opened with the -// // > provided key, it is necessary to perform some operation on the -// // > database (i.e. read from it) and confirm it is success. -// if configuration.readonly { -// code = sqlite3_exec(sqliteConnection, "SELECT COUNT(*) FROM sqlite_master", nil, nil, nil) -// } else { -// code = sqlite3_exec(sqliteConnection, "CREATE TABLE GRDBEncryptionTestTable (id INTEGER); DROP TABLE GRDBEncryptionTestTable;", nil, nil, nil) -// } -// guard code == SQLITE_OK else { -// throw DatabaseError(code: code, message: String.fromCString(sqlite3_errmsg(sqliteConnection))) -// } - - #else - throw DatabaseError(code: SQLITE_MISUSE, message: "encryption is not supported.") - #endif - } - - /// TODO - public func reKey(passphrase: String) throws { - #if SQLITE_HAS_CODEC - let data = passphrase.dataUsingEncoding(NSUTF8StringEncoding)! - let code = sqlite3_rekey(sqliteConnection, data.bytes, Int32(data.length)) - guard code == SQLITE_OK else { - throw DatabaseError(code: code, message: String.fromCString(sqlite3_errmsg(sqliteConnection))) - } - #else - throw DatabaseError(code: SQLITE_MISUSE, message: "encryption is not supported.") - #endif - } - } +#endif // ========================================================================= diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 185f5cad2..c5479ebb8 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -68,9 +68,6 @@ public final class DatabasePool { schemaCache: databaseSchemaCache) serializedDatabase.performSync { db in - if let passphrase = self.passphrase { - try! db.setKey(passphrase) - } for function in self.functions { db.addFunction(function) } @@ -101,8 +98,6 @@ public final class DatabasePool { return store.path } - private var passphrase: String? - // MARK: - WAL Management /// Runs a WAL checkpoint @@ -438,28 +433,4 @@ extension DatabasePool : DatabaseWriter { } dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER) } - - - // MARK: - Encryption - - /// TODO - public func setKey(passphrase: String) throws { - try writer.performSync { db in - try db.setKey(passphrase) - self.readerPool.clear { - self.passphrase = passphrase - } - } - } - - /// TODO - public func reKey(passphrase: String) throws { - try writer.performSync { db in - try db.reKey(passphrase) - self.readerPool.clear { - self.passphrase = passphrase - } - } - } - } diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index 6f5e59da8..fa3befc06 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -281,23 +281,6 @@ extension DatabaseQueue : DatabaseReader { extension DatabaseQueue : DatabaseWriter { - // MARK: - Encryption - - /// TODO - public func setKey(passphrase: String) throws { - try serializedDatabase.performSync { db in - try db.setKey(passphrase) - } - } - - /// TODO - public func reKey(passphrase: String) throws { - try serializedDatabase.performSync { db in - try db.reKey(passphrase) - } - } - - // MARK: - DatabaseWriter Protocol Adoption /// Alias for inDatabase diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index ec4b12a8b..7aad6ecef 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -62,15 +62,6 @@ public protocol DatabaseWriter : DatabaseReader { /// returns when the block has completed. In the example above, the /// insertion is run after the select. func readFromWrite(block: (db: Database) -> Void) - - - // MARK: - Encryption - - /// TODO - func setKey(passphrase: String) throws - - /// TODO - func reKey(passphrase: String) throws } extension DatabaseWriter { diff --git a/Tests/GRDBTestCase.swift b/Tests/GRDBTestCase.swift index 2974be9a8..b2734823f 100644 --- a/Tests/GRDBTestCase.swift +++ b/Tests/GRDBTestCase.swift @@ -7,35 +7,22 @@ class GRDBTestCase: XCTestCase { // Builds a database queue based on dbConfiguration func makeDatabaseQueue(filename: String = "db.sqlite") throws -> DatabaseQueue { - try! NSFileManager.defaultManager().createDirectoryAtPath(dbDirectoryPath, withIntermediateDirectories: true, attributes: nil) + try NSFileManager.defaultManager().createDirectoryAtPath(dbDirectoryPath, withIntermediateDirectories: true, attributes: nil) let dbPath = (dbDirectoryPath as NSString).stringByAppendingPathComponent(filename) let dbQueue = try DatabaseQueue(path: dbPath, configuration: dbConfiguration) - try setUpDatabaseFromTargetConfiguration(dbQueue) try setUpDatabase(dbQueue) return dbQueue } // Builds a database pool based on dbConfiguration func makeDatabasePool(filename: String = "db.sqlite") throws -> DatabasePool { - try! NSFileManager.defaultManager().createDirectoryAtPath(dbDirectoryPath, withIntermediateDirectories: true, attributes: nil) + try NSFileManager.defaultManager().createDirectoryAtPath(dbDirectoryPath, withIntermediateDirectories: true, attributes: nil) let dbPath = (dbDirectoryPath as NSString).stringByAppendingPathComponent(filename) let dbPool = try DatabasePool(path: dbPath, configuration: dbConfiguration) - try setUpDatabaseFromTargetConfiguration(dbPool) try setUpDatabase(dbPool) return dbPool } - #if GRDBCIPHER_USE_ENCRYPTION - let passphrase = "secret" - #endif - - // Subclasses can not override. Here we apply general target configuration - private final func setUpDatabaseFromTargetConfiguration(dbWriter: DatabaseWriter) throws { - #if GRDBCIPHER_USE_ENCRYPTION - try dbWriter.setKey(passphrase) - #endif - } - // Subclasses can override // Default implementation is empty. func setUpDatabase(dbWriter: DatabaseWriter) throws { @@ -62,6 +49,11 @@ class GRDBTestCase: XCTestCase { self.lastSQLQuery = sql // LogSQL(sql) // Uncomment for verbose tests } + + #if GRDBCIPHER_USE_ENCRYPTION + dbConfiguration.passphrase = "secret" + #endif + sqlQueries = [] lastSQLQuery = nil diff --git a/Tests/Public/Core/DatabaseQueue/DatabaseQueueConcurrencyTests.swift b/Tests/Public/Core/DatabaseQueue/DatabaseQueueConcurrencyTests.swift index aa250f78f..d28272602 100644 --- a/Tests/Public/Core/DatabaseQueue/DatabaseQueueConcurrencyTests.swift +++ b/Tests/Public/Core/DatabaseQueue/DatabaseQueueConcurrencyTests.swift @@ -47,6 +47,12 @@ class ConcurrencyTests: GRDBTestCase { func testDeferredTransactionConcurrency() { assertNoError { let dbQueue1 = try makeDatabaseQueue() + #if GRDBCIPHER_USE_ENCRYPTION + // Work around SQLCipher bug when two connections are open to the + // same empty database: make sure the database is not empty before + // running this test + try dbQueue1.execute("CREATE TABLE SQLCipherWorkAround (foo INTEGER)") + #endif let dbQueue2 = try makeDatabaseQueue() // Queue 1 Queue 2 @@ -236,6 +242,12 @@ class ConcurrencyTests: GRDBTestCase { func testBusyCallback() { assertNoError { let dbQueue1 = try makeDatabaseQueue() + #if GRDBCIPHER_USE_ENCRYPTION + // Work around SQLCipher bug when two connections are open to the + // same empty database: make sure the database is not empty before + // running this test + try dbQueue1.execute("CREATE TABLE SQLCipherWorkAround (foo INTEGER)") + #endif let dbQueue2 = try makeDatabaseQueue() // Queue 1 Queue 2 @@ -294,6 +306,12 @@ class ConcurrencyTests: GRDBTestCase { func testReaderDuringDefaultTransaction() { assertNoError { let dbQueue1 = try makeDatabaseQueue() + #if GRDBCIPHER_USE_ENCRYPTION + // Work around SQLCipher bug when two connections are open to the + // same empty database: make sure the database is not empty before + // running this test + try dbQueue1.execute("CREATE TABLE SQLCipherWorkAround (foo INTEGER)") + #endif let dbQueue2 = try makeDatabaseQueue() // Here we test that a reader can read while a writer is writing. @@ -354,6 +372,12 @@ class ConcurrencyTests: GRDBTestCase { func testReaderInDeferredTransactionDuringDefaultTransaction() { assertNoError { let dbQueue1 = try makeDatabaseQueue() + #if GRDBCIPHER_USE_ENCRYPTION + // Work around SQLCipher bug when two connections are open to the + // same empty database: make sure the database is not empty before + // running this test + try dbQueue1.execute("CREATE TABLE SQLCipherWorkAround (foo INTEGER)") + #endif let dbQueue2 = try makeDatabaseQueue() // The `SELECT * FROM stuffs` statement of Queue 2 prevents Queue 1