|
| 1 | +package com.powersync |
| 2 | + |
| 3 | +import androidx.test.ext.junit.runners.AndroidJUnit4 |
| 4 | +import androidx.test.platform.app.InstrumentationRegistry |
| 5 | +import androidx.sqlite.SQLiteException |
| 6 | +import androidx.sqlite.execSQL |
| 7 | +import app.cash.turbine.turbineScope |
| 8 | +import com.powersync.db.schema.Schema |
| 9 | +import com.powersync.encryption.AndroidEncryptedDatabaseFactory |
| 10 | +import com.powersync.encryption.Key |
| 11 | +import com.powersync.testutils.UserRow |
| 12 | +import kotlinx.coroutines.* |
| 13 | +import kotlinx.coroutines.runBlocking |
| 14 | +import kotlinx.coroutines.test.runTest |
| 15 | +import org.junit.After |
| 16 | +import org.junit.Assert.* |
| 17 | +import org.junit.Before |
| 18 | +import org.junit.Test |
| 19 | +import org.junit.runner.RunWith |
| 20 | + |
| 21 | +@RunWith(AndroidJUnit4::class) |
| 22 | +class EncryptedDatabaseTest { |
| 23 | + |
| 24 | + @Test |
| 25 | + fun testEncryptedDatabase() = |
| 26 | + runTest { |
| 27 | + val context = InstrumentationRegistry.getInstrumentation().targetContext |
| 28 | + |
| 29 | + val database = PowerSyncDatabase( |
| 30 | + factory = AndroidEncryptedDatabaseFactory( |
| 31 | + context, |
| 32 | + Key.Passphrase("mykey") |
| 33 | + ), |
| 34 | + schema = Schema(UserRow.table), |
| 35 | + dbFilename = "encrypted_test", |
| 36 | + ) |
| 37 | + |
| 38 | + assertEquals("chacha20", database.get("PRAGMA cipher") { it.getString(0)!! }) |
| 39 | + |
| 40 | + database.execute( |
| 41 | + "INSERT INTO users (id, name, email) VALUES (uuid(), ?, ?)", |
| 42 | + listOf("Test", "test@example.org"), |
| 43 | + ) |
| 44 | + database.close() |
| 45 | + |
| 46 | + val unencryptedFactory = DatabaseDriverFactory(context) |
| 47 | + val unencrypted = unencryptedFactory.openConnection("encrypted_test", null, false) |
| 48 | + |
| 49 | + try { |
| 50 | + unencrypted.execSQL("SELECT * FROM sqlite_schema") |
| 51 | + throw IllegalStateException("Was able to read schema from encrypted database without supplying a key") |
| 52 | + } catch (_: SQLiteException) { |
| 53 | + // Expected |
| 54 | + } |
| 55 | + unencrypted.close() |
| 56 | + } |
| 57 | +} |
0 commit comments