diff --git a/CHANGELOG.md b/CHANGELOG.md index cd6e7f59..2fe0ba23 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,10 @@ IzzyOnDroid) and used as the GitHub Release notes. ## [Unreleased] +### Security + +- Someone who only knows your duress PIN can no longer set the clock forward to make the next real unlock delete old notes from your trash early: the decoy vault now has its own trash timer. Turning the duress PIN off or setting a new one now checks that the old decoy database is really deleted and fails otherwise. Changing PINs inside the decoy vault is refused after the same pause as in the real vault. The vault no longer opens when the screen switches off and on while the PIN is still being checked. + ### Added - Encly for Windows, macOS and Linux (MSI, DMG, DEB and a Flatpak bundle): the same vault, notes and security as on the phone, with list and note side by side, note tabs, several windows, keyboard shortcuts and a menu bar, export to PDF and print, and the PIN's device key in the system's secret store ([#85](https://github.com/pasichDev/Encly/issues/85), [#106](https://github.com/pasichDev/Encly/issues/106)). diff --git a/PRIVACY.md b/PRIVACY.md index d727665b..2cfdf5ad 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -30,6 +30,37 @@ ignore these requests, so use one you trust. This data is stored in Encly's private app storage. Android cloud backup and device-to-device transfer are disabled for it, so it is not copied to Google Drive or another phone. +## Duress PIN and decoy vault (optional) + +In **Settings → Security** you can set a **duress PIN**: a second PIN, typed on the lock screen +like any other. Instead of your real vault it opens a **decoy vault**, a separate vault that +starts empty and works like the real one, so you can show someone "the app" without showing your +notes. It erases nothing, and your real vault stays closed and unchanged while the decoy is open. +It is not meant to hide your real vault from someone who examines the phone's storage. + +What it keeps on your device, in the same private app storage as everything else: + +- **The decoy vault's notes, tags and tasks**, in a second database file of its own + (`vault_b.db`), encrypted with SQLCipher under its own random key. The file is created the + first time the duress PIN is used and kept between locks until you remove it. +- **Two entries of security metadata:** the encrypted key envelope that the duress PIN opens, and + the decoy vault's key sealed under your real vault's key (so changing the duress PIN keeps the + decoy notes). Both exist, with the same size, whether or not you set a duress PIN, so the + metadata does not show whether you did. The duress PIN itself is never stored. +- **The same app settings** (theme, sort order, editor font, auto-lock delay, keyboard privacy) + are used in both vaults. + +Inside the decoy vault, what belongs to your real vault does not work: changing the PINs, +fingerprint unlock, the recovery phrase, encrypted backups and "Erase all data". Fingerprint +unlock and the recovery phrase on the lock screen always open the real vault. An encrypted backup +never contains decoy notes. Markdown export and notes import do work there, on the decoy vault's +own notes, and the files they make are yours to keep or delete (see the export sections below). + +Turning the duress PIN off (Settings → Security, after your PIN and a confirmation) deletes the +decoy vault and its notes. The wipe PIN and **Erase all data** delete the decoy vault together with +the real one. See [SECURITY.md → Duress PIN](SECURITY.md#duress-pin) for the technical details and +what it does not hide. + ## Permissions | Permission | Why | @@ -127,9 +158,9 @@ in a readable format first. ## Deleting your data Uninstalling Encly, or clearing its storage in Android settings, permanently deletes all of -it, and so does **Settings → Security → Erase all data**. There is no copy anywhere else, apart -from encrypted backups you exported yourself. If you did not keep a recovery seed, a forgotten -PIN also means the data cannot be recovered. +it, and so does **Settings → Security → Erase all data** (the decoy vault too, if you have one). +There is no copy anywhere else, apart from encrypted backups you exported yourself. If you did not +keep a recovery seed, a forgotten PIN also means the data cannot be recovered. ## Children diff --git a/SECURITY.md b/SECURITY.md index 403cbab5..738ce284 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -290,11 +290,14 @@ meant for "open the app and show me", not against a forensic examination. on every miss is locked out, escalating as above, even right after the duress PIN opened the decoy vault. Without that, someone who was given the duress PIN could guess at the real PIN 4 times, type the duress PIN to reset the lockout, and repeat without limit. The cost is a - tell after that many misses (a lockout sooner than the screen suggests), and a store-level - one: after misses, a duress unlock leaves `pin.strikes` in the state file with no lockout - failures, which a real PIN unlock never does, so anyone who can read the app's private files - can then see that a duress PIN exists and that the last unlock was a non-PIN one. A duress - unlock with no misses before it leaves the same entries as a real PIN unlock. + store-level tell: after misses, a duress unlock leaves `pin.strikes` in the state file with no + matching lockout failures, which a real PIN unlock never does, so anyone who can read the app's + private files can see that a duress PIN exists. The entry stays until the real PIN is typed + again (or a new PIN is set, or the wipe PIN erases the vault): later misses, fingerprint + unlocks and recovery-phrase unlocks do not clear it, so someone who unlocks mostly with a + fingerprint can carry it for weeks. On screen, from the 10th strike on every miss is locked out + (as above). A duress unlock with no misses before it leaves the same entries as a real PIN + unlock. - **Rules.** 6 to 12 digits, different from the PIN and from the wipe PIN (checked by opening their slots with it); a wipe PIN equal to the duress PIN is refused, and so is changing the PIN to the duress PIN, since either would silently orphan the decoy notes. A reset of the PIN's @@ -305,12 +308,20 @@ meant for "open the app and show me", not against a forensic examination. - **Inside the decoy vault.** Notes, tags, tasks, trash, search, sorting and appearance work as usual. Settings shows the same entries as in the real vault, and everything that belongs to the real vault is refused by the security layer and fails like a storage error would, with - the usual generic message: changing the PIN, the wipe and duress PINs, fingerprint unlock, the - recovery phrase, encrypted backups (export and import) and "Erase all data". A PIN re-check - there accepts the duress PIN only, so the decoy vault itself cannot be used to test guesses - of the real PIN; on the lock screen the strikes above bound them. Fingerprint unlock and the recovery phrase on the lock screen always open the real + the usual generic message: changing the PIN, the wipe and duress PINs, the recovery phrase, + encrypted backups (export and import) and "Erase all data" (fingerprint unlock is the + exception, see the next item). A PIN re-check there accepts the duress PIN only, so the decoy + vault itself cannot be used to test guesses of the real PIN; on the lock screen the strikes + above bound them. A refused PIN change there runs the same KDF step as the real vault's own + work (one PBKDF2 and Keystore run over the PIN typed), so the refusal does not come back + faster. Fingerprint unlock and the recovery phrase on the lock screen always open the real vault, and nothing in the decoy vault offers a way to switch: to change vaults, lock and type the other PIN. App settings (theme, sorting, font, auto-lock, keyboard privacy) are shared. +- **Fingerprint in the decoy vault (a known tell).** Settings there shows fingerprint unlock as + it is set in the app, but the decoy vault cannot use it: the PIN re-check dialogs (allowing + screenshots, Markdown export, confirming a weaker setting, erase) have no fingerprint key, + although the real vault's offer one, and turning the fingerprint switch on or off fails at once + with an error of its own and no system fingerprint prompt. Someone who knows the app can notice. - **Session isolation.** Only one database is open at a time. Every repository is bound to the opening it was created in (a lease revoked before Room closes), so nothing created in one vault reads or writes the other. Opening the other vault starts a new epoch, so the note that @@ -318,7 +329,10 @@ meant for "open the app and show me", not against a forensic examination. - **Failures never fall back.** A decoy database that does not open fails the unlock; it is neither deleted nor replaced by the real vault. Turning the duress PIN off (after the PIN and a confirmation) forgets the decoy key first and then deletes `vault_b.db`; a kill in between - leaves a file nothing can open, which the next duress PIN set replaces. + leaves a file nothing can open, which the next duress PIN set replaces. The delete is + checked: the database file and its `-wal`, `-shm`, `-journal` and lock files must be gone, or + turning the duress PIN off reports a failure, and setting a new duress PIN (which also starts + by deleting an old `vault_b.db`) fails instead of leaving a PIN that opens a stale file. - **Wipe PIN.** The erase also replaces both decoy entries with random bytes and deletes `vault_b.db` with the real database: the empty vault has no decoy vault either. - **Limits.** The decoy vault does not hide that the real one exists from a forensic look: the @@ -328,7 +342,38 @@ meant for "open the app and show me", not against a forensic examination. "Important limitations") finds the duress PIN as well. - **Downgrade.** Older builds ignore both entries and the second database and keep opening the real vault. A PIN changed in an older build gets a new salt, which silently turns the duress - PIN off; the decoy notes come back once it is set again in this version. + PIN off; the decoy notes come back once it is set again in this version. An erase in 2.1.x + (the wipe PIN or "Erase all data") predates the decoy vault and does not know `vault_b.db`, so + the file can stay on disk (encrypted) after it. + +#### What an observer can and cannot tell + +From the review of 2026-11-21 (someone made to see the app, or reading an image of the phone's +storage). + +Checked and safe: + +- The state file has the same entries and sizes with or without a duress PIN, through setting it, + changing it, turning it off, a PIN change and the erase. +- Every PIN attempt costs the same (one KDF run, all three slots tried), whichever PIN it is. +- No data of the real vault is reachable from the decoy: it opens only its own database, every + operation of the real vault is refused there, and its PIN re-check accepts the duress PIN only. +- Nothing outside the two databases records which vault was used: the shared settings hold + appearance and privacy choices, the what's-new version and the trash purge times (the decoy + vault's own one is written only after it purged), and there are no notifications, widgets, + shortcuts or attachments on disk. + +Still visible: + +- Fingerprint in the decoy vault (above). +- `pin.strikes` in the state file after a duress unlock that followed misses (above). +- Encrypted backups exported earlier are named `encly-backup-*` in shared storage and can show in + the file picker's recent list, which the decoy vault's Import screen opens. The decoy vault + itself says "never exported". +- "What's new" and the trash notice after an update are shown to whichever vault is unlocked + first, so a duress unlock can use them up before the real vault shows them. +- The second database file, its size and timestamps (see Limits). +- The downgrade note above, for someone who goes back to 2.1.x. ### Biometric slot diff --git a/app/src/test/java/com/pasich/encly/core/platform/AlarmMainThreadTimerTest.kt b/app/src/test/java/com/pasich/encly/core/platform/AlarmMainThreadTimerTest.kt index 1406a671..9d3eb1be 100644 --- a/app/src/test/java/com/pasich/encly/core/platform/AlarmMainThreadTimerTest.kt +++ b/app/src/test/java/com/pasich/encly/core/platform/AlarmMainThreadTimerTest.kt @@ -4,6 +4,7 @@ import android.app.AlarmManager import android.app.Application import android.content.Context import android.os.Looper +import android.os.SystemClock import androidx.test.core.app.ApplicationProvider import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse @@ -84,6 +85,45 @@ class AlarmMainThreadTimerTest { assertNull(shadowOf(alarms).nextScheduledAlarm) } + @Test + fun theAlarmsOfTheFifteenAndThirtyMinuteDelaysAreSetForThoseDelays() { + listOf(15L, 30L).forEach { minutes -> + val delay = TimeUnit.MINUTES.toMillis(minutes) + val before = SystemClock.elapsedRealtime() + + val cancel = timer.schedule(delay) { runs++ } + + val alarm = shadowOf(alarms).nextScheduledAlarm!! + assertTrue( + "$minutes min: ${alarm.triggerAtTime - before}", + alarm.triggerAtTime - before in delay..delay + 1_000, + ) + assertEquals(AlarmManager.ELAPSED_REALTIME_WAKEUP, alarm.type) + assertTrue(alarm.isAllowWhileIdle) + cancel() + assertNull(shadowOf(alarms).nextScheduledAlarm) + } + } + + @Test + fun aLongDelayHandlerThatNeverRanLeavesTheAlarmToRunTheAction() { + timer.schedule(TimeUnit.MINUTES.toMillis(30)) { runs++ } + val id = alarmId() + + pass(TimeUnit.MINUTES.toMillis(29)) // a frozen process: in real life nothing would run here + + assertEquals("not yet", 0, runs) + assertTrue(AlarmMainThreadTimer.fire(id)) + assertEquals(1, runs) + } + + @Test + fun anAlarmThatOutlivedItsProcessFindsNoActionAndDoesNothing() { + // The process died with the alarm pending: the new process has no action under that id. + assertFalse(AlarmMainThreadTimer.fire(Int.MAX_VALUE - 7)) + assertEquals(0, runs) + } + private fun alarmId(): Int = shadowOf(shadowOf(alarms).nextScheduledAlarm!!.operation).savedIntent.getIntExtra(AwayLockReceiver.EXTRA_ID, -1) } diff --git a/app/src/test/java/com/pasich/encly/core/security/LongAutoLockAlarmTest.kt b/app/src/test/java/com/pasich/encly/core/security/LongAutoLockAlarmTest.kt new file mode 100644 index 00000000..90e191a3 --- /dev/null +++ b/app/src/test/java/com/pasich/encly/core/security/LongAutoLockAlarmTest.kt @@ -0,0 +1,170 @@ +package com.pasich.encly.core.security + +import android.app.AlarmManager +import android.app.Application +import android.content.Context +import android.os.Looper +import android.os.SystemClock +import androidx.lifecycle.LifecycleOwner +import androidx.test.core.app.ApplicationProvider +import com.pasich.encly.core.platform.AlarmMainThreadTimer +import com.pasich.encly.core.platform.AwayLockReceiver +import com.pasich.encly.core.platform.HandlerMainThreadTimer +import com.pasich.encly.testutil.InMemoryKeyValueStore +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.Mockito.mock +import org.mockito.Mockito.never +import org.mockito.Mockito.times +import org.mockito.Mockito.verify +import org.mockito.Mockito.`when` +import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import java.util.concurrent.TimeUnit + +/** + * The 15 and 30 minute auto-lock delays (issue #131) on the real alarm timer and the real stored setting: the + * delay survives a process death, the wake-up alarm locks a frozen process, and the screen turning off or the + * keyguard coming up ends the wait at once. + */ +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [35], application = Application::class) +class LongAutoLockAlarmTest { + private val context: Context get() = ApplicationProvider.getApplicationContext() + private val alarms: AlarmManager get() = context.getSystemService(AlarmManager::class.java) + private val owner = mock(LifecycleOwner::class.java) + private val delays = listOf(AutoLockDelay.MINUTES_15, AutoLockDelay.MINUTES_30) + + private class FakeDeviceLock : DeviceLockWatcher { + var locked = false + var screenOn = true + private var onScreenOff: (() -> Unit)? = null + + override fun isDeviceLocked(): Boolean = locked + + override fun isScreenOn(): Boolean = screenOn + + override fun watchScreenOff(onScreenOff: () -> Unit): () -> Unit { + this.onScreenOff = onScreenOff + return { this.onScreenOff = null } + } + + fun screenOff() { + screenOn = false + onScreenOff?.invoke() + } + } + + private fun pass(ms: Long) = shadowOf(Looper.getMainLooper()).idleFor(ms, TimeUnit.MILLISECONDS) + + private fun alarmId(): Int = + shadowOf(shadowOf(alarms).nextScheduledAlarm!!.operation).savedIntent.getIntExtra(AwayLockReceiver.EXTRA_ID, -1) + + private class Process(val security: SecurityManager, val manager: SessionLockManager) + + /** A new process: the stored delay is read again, the open vault and every timer of the old one are gone. */ + private fun processWith(prefs: InMemoryKeyValueStore, deviceLock: FakeDeviceLock): Process { + val security = mock(SecurityManager::class.java) + `when`(security.isLockable()).thenReturn(true) + val manager = SessionLockManager( + security, + deviceLock, + autoLock = AutoLock(prefs), + mainThread = AlarmMainThreadTimer(context, HandlerMainThreadTimer()), + ) + manager.requireUnlock() + manager.onStart(owner) + `when`(security.isDatabaseUnlocked()).thenReturn(true) + assertTrue(manager.onUnlocked()) + return Process(security, manager) + } + + @Test + fun theStoredDelayIsTheAlarmThatIsSetAfterAProcessRestart() { + delays.forEach { delay -> + val prefs = InMemoryKeyValueStore() + AutoLock(prefs).setDelay(delay) + val process = processWith(prefs, FakeDeviceLock()) + val before = SystemClock.elapsedRealtime() + + process.manager.onStop(owner) + + val alarm = shadowOf(alarms).nextScheduledAlarm + assertNotNull(alarm) + assertTrue(alarm!!.triggerAtTime - before in delay.millis..delay.millis + 1_000) + process.manager.onStart(owner) + assertNull("coming back cancels the alarm", shadowOf(alarms).nextScheduledAlarm) + verify(process.security, never()).lock() + } + } + + @Test + fun theAlarmLocksAFrozenProcessAndTheHandlerThatFollowsDoesNotLockAgain() { + delays.forEach { delay -> + val process = processWith(InMemoryKeyValueStore().also { AutoLock(it).setDelay(delay) }, FakeDeviceLock()) + process.manager.onStop(owner) + + assertTrue(AlarmMainThreadTimer.fire(alarmId())) + + verify(process.security).lock() + assertTrue(process.manager.locked.value) + pass(delay.millis + 1_000) + verify(process.security, times(1)).lock() + } + } + + @Test + fun theHandlerLocksAtTheDelayWhenTheProcessIsNotFrozenAndTheAlarmIsDropped() { + delays.forEach { delay -> + val process = processWith(InMemoryKeyValueStore().also { AutoLock(it).setDelay(delay) }, FakeDeviceLock()) + process.manager.onStop(owner) + + pass(delay.millis - 1) + verify(process.security, never()).lock() + pass(2) + + verify(process.security).lock() + assertNull(shadowOf(alarms).nextScheduledAlarm) + } + } + + @Test + fun theScreenTurningOffInsideTheDelayLocksAtOnceAndCancelsTheAlarm() { + delays.forEach { delay -> + val deviceLock = FakeDeviceLock() + val process = processWith(InMemoryKeyValueStore().also { AutoLock(it).setDelay(delay) }, deviceLock) + process.manager.onStop(owner) + pass(delay.millis / 2) + + deviceLock.screenOff() + + verify(process.security).lock() + assertTrue(process.manager.locked.value) + assertNull(shadowOf(alarms).nextScheduledAlarm) + pass(delay.millis) + verify(process.security, times(1)).lock() + } + } + + @Test + fun theKeyguardUpOnReturnInsideTheDelayLocksTheVault() { + delays.forEach { delay -> + val deviceLock = FakeDeviceLock() + val process = processWith(InMemoryKeyValueStore().also { AutoLock(it).setDelay(delay) }, deviceLock) + process.manager.onStop(owner) + pass(delay.millis / 3) + deviceLock.locked = true + + process.manager.onStart(owner) + + verify(process.security).lock() + assertTrue(process.manager.locked.value) + assertTrue(process.manager.isDeviceLocked()) + assertNull(shadowOf(alarms).nextScheduledAlarm) + } + } +} diff --git a/core/database/src/androidHostTest/kotlin/com/pasich/encly/data/database/SecureDatabaseManagerTest.kt b/core/database/src/androidHostTest/kotlin/com/pasich/encly/data/database/SecureDatabaseManagerTest.kt index ca464a2f..d35fc2eb 100644 --- a/core/database/src/androidHostTest/kotlin/com/pasich/encly/data/database/SecureDatabaseManagerTest.kt +++ b/core/database/src/androidHostTest/kotlin/com/pasich/encly/data/database/SecureDatabaseManagerTest.kt @@ -150,4 +150,35 @@ class SecureDatabaseManagerTest { (files(VaultFile.PRIMARY) + files(VaultFile.DECOY)).forEach { assertFalse(it.path, it.exists()) } } + + /** Makes the side file at [suffix] something a delete cannot remove: a directory with a file in it. */ + private fun makeUndeletable(vault: VaultFile, suffix: String) { + val stuck = File(context.getDatabasePath(vault.fileName).path + suffix) + stuck.delete() + stuck.mkdirs() + File(stuck, "held").writeBytes(byteArrayOf(1)) + } + + @Test + fun wipeIfClosedReportsAFileThatCouldNotBeDeletedAndStillRemovesTheOthers() { + createFiles(VaultFile.DECOY) + makeUndeletable(VaultFile.DECOY, "-wal") + + assertFalse("a file stayed, so it is not gone", manager.wipeIfClosed(only = VaultFile.DECOY)) + + assertFalse(File(context.getDatabasePath(VaultFile.DECOY.fileName).path).exists()) + assertFalse(File(context.getDatabasePath(VaultFile.DECOY.fileName).path + "-journal").exists()) + File(context.getDatabasePath(VaultFile.DECOY.fileName).path + "-wal").deleteRecursively() + } + + @Test + fun wipeIfClosedOfOneVaultIsTrueWhenOnlyTheOtherVaultHasAStuckFile() { + createFiles(VaultFile.DECOY) + createFiles(VaultFile.PRIMARY) + makeUndeletable(VaultFile.PRIMARY, "-shm") + + assertTrue(manager.wipeIfClosed(only = VaultFile.DECOY)) + + File(context.getDatabasePath(VaultFile.PRIMARY.fileName).path + "-shm").deleteRecursively() + } } diff --git a/core/database/src/commonMain/kotlin/com/pasich/encly/data/database/SecureDatabaseManager.kt b/core/database/src/commonMain/kotlin/com/pasich/encly/data/database/SecureDatabaseManager.kt index c834938b..bdc815cc 100644 --- a/core/database/src/commonMain/kotlin/com/pasich/encly/data/database/SecureDatabaseManager.kt +++ b/core/database/src/commonMain/kotlin/com/pasich/encly/data/database/SecureDatabaseManager.kt @@ -153,20 +153,32 @@ public class SecureDatabaseManager(private val platform: DatabasePlatform) : Dat } } - private fun deleteDatabaseFiles(file: VaultFile) { + /** Deletes the files of [file]; true when none of them is there afterwards (checked, not assumed). */ + private fun deleteDatabaseFiles(file: VaultFile): Boolean { val dbFile = try { platform.databasePath(file).toString() } catch (_: Exception) { - return + return false } + var gone = true // Each file on its own: one that cannot be deleted must not spare the others. FILE_SUFFIXES.forEach { suffix -> + val path = Path(dbFile + suffix) try { - SystemFileSystem.delete(Path(dbFile + suffix), mustExist = false) + SystemFileSystem.delete(path, mustExist = false) } catch (_: Exception) { - // Best effort, as File.delete was: the next wipe tries again. + // The check below decides: the next wipe tries again. } + if (isStillThere(path)) gone = false } + return gone + } + + /** A path that cannot be looked at counts as still there. */ + private fun isStillThere(path: Path): Boolean = try { + SystemFileSystem.exists(path) + } catch (_: Exception) { + true } /** @@ -207,15 +219,16 @@ public class SecureDatabaseManager(private val platform: DatabasePlatform) : Dat /** * Deletes the database files unless the database is open, checked and done under the same * lock [unlockDatabase] holds, so a database being opened (or just created) meanwhile is - * never deleted. True when they were deleted. + * never deleted. True when they were deleted: every file is checked to be gone, so a file + * that could not be removed is reported, not assumed away. * * With [only], just that file goes, refused only while that one is open: the decoy vault's * database is deleted from a session of the real vault, whose file is never touched. */ public fun wipeIfClosed(only: VaultFile? = null): Boolean = synchronized(lock) { if (isUnlocked && (only == null || openFile == only)) return@synchronized false - (only?.let(::listOf) ?: VaultFile.entries).forEach(::deleteDatabaseFiles) - true + // Every file is tried, even after one that stays. + (only?.let(::listOf) ?: VaultFile.entries).map(::deleteDatabaseFiles).all { it } } private companion object { diff --git a/core/security/src/commonMain/kotlin/com/pasich/encly/core/backup/BackupSettings.kt b/core/security/src/commonMain/kotlin/com/pasich/encly/core/backup/BackupSettings.kt index ee3354c8..dfca1c29 100644 --- a/core/security/src/commonMain/kotlin/com/pasich/encly/core/backup/BackupSettings.kt +++ b/core/security/src/commonMain/kotlin/com/pasich/encly/core/backup/BackupSettings.kt @@ -150,6 +150,7 @@ public object BackupSettings { "first-run setup marker: a staged restore is being imported into this install's vault", "whats_new_last_seen_version" to "what's-new marker of this install", "trash_last_purge_at" to "when the trash was last emptied of old notes on this install", + "trash_last_purge_at_d" to "the decoy vault's own trash purge time on this install", "backup_last_export_at" to "describes an export made from this install", "appearance_migrated_v1" to "one-time migration marker of this install", "window_width" to "device-bound desktop window geometry", diff --git a/core/security/src/commonMain/kotlin/com/pasich/encly/core/security/AuthenticationManager.kt b/core/security/src/commonMain/kotlin/com/pasich/encly/core/security/AuthenticationManager.kt index 51dbb5a4..cbd58f75 100644 --- a/core/security/src/commonMain/kotlin/com/pasich/encly/core/security/AuthenticationManager.kt +++ b/core/security/src/commonMain/kotlin/com/pasich/encly/core/security/AuthenticationManager.kt @@ -947,6 +947,26 @@ public class AuthenticationManager( } } + /** + * One KDF run over [pin] with a random salt, result thrown away: what a decoy session spends before it + * refuses to change a PIN, so that the refusal takes as long as the real vault's own work. Nothing is + * read from or written to the store, and a failing key store is no different from a working one here. + * [pin] stays the caller's to wipe. + */ + internal fun spendPinCost(pin: CharArray) { + if (!isWellFormed(pin)) return + val salt = Crypto.randomBytes(PIN_SALT_SIZE) + try { + derivePinKeys(pin, salt, activeKeySlot()).wipe() + } catch (_: PinFactorException) { + // The cost was spent up to the failure: nothing else to do. + } catch (_: CryptoException) { + // Same. + } finally { + SensitiveDataCleaner.clear(salt) + } + } + /** HMAC of `salt ‖ pin` under the key in [keySlot]; the caller wipes the result. */ private fun hardwareHalf(pin: CharArray, salt: ByteArray, keySlot: PinKeySlot): ByteArray { val macInput = ByteArray(salt.size + pin.size) diff --git a/core/security/src/commonMain/kotlin/com/pasich/encly/core/security/SecurityManager.kt b/core/security/src/commonMain/kotlin/com/pasich/encly/core/security/SecurityManager.kt index a2061d1d..aaa9d2e7 100644 --- a/core/security/src/commonMain/kotlin/com/pasich/encly/core/security/SecurityManager.kt +++ b/core/security/src/commonMain/kotlin/com/pasich/encly/core/security/SecurityManager.kt @@ -247,6 +247,8 @@ public class SecurityManager( */ public fun changePin(pin: CharArray): PinChange { if (isDecoySession()) { + // Refused, but after the same KDF run the real vault does: an instant "no" would tell. + authenticationManager.spendPinCost(pin) SensitiveDataCleaner.clear(pin) return PinChange.FAILED } @@ -579,7 +581,13 @@ public class SecurityManager( * PIN. [pin] is wiped. */ public fun configureWipePin(pin: CharArray): WipePinChange = try { - if (!primarySessionOpen()) WipePinChange.FAILED else authenticationManager.configureWipePin(pin) + if (primarySessionOpen()) { + authenticationManager.configureWipePin(pin) + } else { + // In a decoy session the refusal costs the same KDF run as the real vault's set-up. + if (isDecoySession()) authenticationManager.spendPinCost(pin) + WipePinChange.FAILED + } } finally { SensitiveDataCleaner.clear(pin) } @@ -597,6 +605,8 @@ public class SecurityManager( val dek = primarySessionKeyCopy() return try { if (dek == null) { + // In a decoy session the refusal costs the same KDF run as the real vault's set-up. + if (isDecoySession()) authenticationManager.spendPinCost(pin) DuressPinChange.FAILED } else { authenticationManager.configureDuressPin(pin, dek) { diff --git a/core/security/src/commonMain/kotlin/com/pasich/encly/core/security/SessionLockManager.kt b/core/security/src/commonMain/kotlin/com/pasich/encly/core/security/SessionLockManager.kt index a1b81b7c..217e3771 100644 --- a/core/security/src/commonMain/kotlin/com/pasich/encly/core/security/SessionLockManager.kt +++ b/core/security/src/commonMain/kotlin/com/pasich/encly/core/security/SessionLockManager.kt @@ -204,7 +204,9 @@ public class SessionLockManager( // keyguard that came up) is already gone: neither the delay nor the picker grace may keep the vault open. // The watchers of suspend() only hear a screen-off that comes later. if (!deviceLock.isScreenOn() || deviceLock.isDeviceLocked()) { - if (isOpenAndLockable()) relock() + // Counted even with nothing open: an unlock still checking the PIN must not be published after the + // screen comes back on, which an insecure keyguard would not report as locked. + lockNow() return } val now = clock() diff --git a/core/security/src/jvmAndAndroidTest/kotlin/com/pasich/encly/core/security/DecoyRefusalCostTest.kt b/core/security/src/jvmAndAndroidTest/kotlin/com/pasich/encly/core/security/DecoyRefusalCostTest.kt new file mode 100644 index 00000000..63ef193d --- /dev/null +++ b/core/security/src/jvmAndAndroidTest/kotlin/com/pasich/encly/core/security/DecoyRefusalCostTest.kt @@ -0,0 +1,106 @@ +package com.pasich.encly.core.security + +import com.pasich.encly.testutil.DuressVaultFixture +import com.pasich.encly.testutil.DuressVaultFixture.Companion.DURESS_PIN +import com.pasich.encly.testutil.DuressVaultFixture.Companion.PIN +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +/** + * In a decoy session the PIN changes are refused, but not faster than the real vault does them: each + * refusal runs one KDF run (one hardware-half call is the count of runs) over the PIN it was given, so the + * pause the real vault shows is there too. + */ +class DecoyRefusalCostTest { + private lateinit var vault: DuressVaultFixture + + @Before + fun setUp() { + vault = DuressVaultFixture(withDuressPin = true) + } + + private fun openDecoy() { + assertEquals(VaultUnlockResult.SUCCESS, vault.security.unlockWithPin(DURESS_PIN.toCharArray())) + assertTrue(vault.security.isDecoySession()) + } + + private fun openReal() { + assertEquals(VaultUnlockResult.SUCCESS, vault.security.unlockWithPin(PIN.toCharArray())) + assertTrue(!vault.security.isDecoySession()) + } + + /** The KDF runs [action] made. */ + private fun runs(action: () -> Unit): Int { + val before = vault.factor.calls + action() + return vault.factor.calls - before + } + + @Test + fun refusingAPinChangeInADecoySessionRunsTheKdfOnceAndStillRefuses() { + openDecoy() + val pin = "246802".toCharArray() + + var result: PinChange? = null + val runs = runs { result = vault.security.changePin(pin) } + + assertEquals(PinChange.FAILED, result) + assertEquals(1, runs) + assertTrue("the PIN is wiped", pin.all { it == '\u0000' }) + } + + @Test + fun refusingAWipePinInADecoySessionRunsTheKdfOnceAndStillRefuses() { + openDecoy() + var result: WipePinChange? = null + + val runs = runs { result = vault.security.configureWipePin("246802".toCharArray()) } + + assertEquals(WipePinChange.FAILED, result) + assertEquals(1, runs) + } + + @Test + fun refusingADuressPinInADecoySessionRunsTheKdfOnceAndStillRefuses() { + openDecoy() + var result: DuressPinChange? = null + + val runs = runs { result = vault.security.configureDuressPin("246802".toCharArray()) } + + assertEquals(DuressPinChange.FAILED, result) + assertEquals(1, runs) + } + + @Test + fun theRealVaultsOwnWorkRunsTheSameOneKdfRun() { + openReal() + + assertEquals(1, runs { vault.security.changePin("246802".toCharArray()) }) + assertEquals(1, runs { vault.security.configureWipePin("357913".toCharArray()) }) + assertEquals(1, runs { vault.security.configureDuressPin("468024".toCharArray()) }) + } + + @Test + fun aDecoyRefusalWithAFailingKeyStoreStillRefusesTheSameWay() { + openDecoy() + vault.factor.failing = true + + assertEquals(PinChange.FAILED, vault.security.changePin("246802".toCharArray())) + assertEquals(WipePinChange.FAILED, vault.security.configureWipePin("246802".toCharArray())) + assertEquals(DuressPinChange.FAILED, vault.security.configureDuressPin("246802".toCharArray())) + } + + @Test + fun theRefusalsLeaveTheStateFileAsItWas() { + openDecoy() + val before = vault.file.readBytes() + + vault.security.changePin("246802".toCharArray()) + vault.security.configureWipePin("246802".toCharArray()) + vault.security.configureDuressPin("246802".toCharArray()) + + assertTrue(before.contentEquals(vault.file.readBytes())) + } +} diff --git a/core/security/src/jvmAndAndroidTest/kotlin/com/pasich/encly/core/security/DuressSetupInterruptionTest.kt b/core/security/src/jvmAndAndroidTest/kotlin/com/pasich/encly/core/security/DuressSetupInterruptionTest.kt new file mode 100644 index 00000000..69742ed1 --- /dev/null +++ b/core/security/src/jvmAndAndroidTest/kotlin/com/pasich/encly/core/security/DuressSetupInterruptionTest.kt @@ -0,0 +1,211 @@ +package com.pasich.encly.core.security + +import com.pasich.encly.testutil.DuressVaultFixture +import com.pasich.encly.testutil.DuressVaultFixture.Companion.DURESS_PIN +import com.pasich.encly.testutil.DuressVaultFixture.Companion.OTHER_DURESS_PIN +import com.pasich.encly.testutil.DuressVaultFixture.Companion.PIN +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Test +import java.io.IOException + +/** + * Setting the duress PIN killed at each stage (issue #131). The set-up has two steps: `onNewVault` + * (deletes a decoy database nothing can open any more), then one atomic write of the duress slot + * and `decoy.key` together. The decoy database itself is created later, by the first unlock with + * the duress PIN. After a kill and a restart the real vault must open with the real PIN, and the + * duress PIN must either open the decoy vault fully or be a plain wrong PIN, never in between. + */ +class DuressSetupInterruptionTest { + private class ProcessDeath : RuntimeException("process killed") + + private fun DuressVaultFixture.unlockReal(): VaultUnlockResult { + security.lock() + return security.unlockWithPin(PIN.toCharArray()) + } + + private fun DuressVaultFixture.assertRealVaultOpensWithItsOwnKey() { + assertEquals(VaultUnlockResult.SUCCESS, unlockReal()) + assertEquals(VaultKind.PRIMARY, db.open) + assertEquals(bootstrap.toList(), db.opens.last().key) + assertFalse(security.isDecoySession()) + } + + private fun DuressVaultFixture.assertDuressPinIsJustWrong() { + security.lock() + assertEquals(VaultUnlockResult.INVALID_CREDENTIAL, security.unlockWithPin(DURESS_PIN.toCharArray())) + assertFalse(security.isDatabaseUnlocked()) + assertFalse("no decoy database was made", VaultKind.DECOY in db.files) + assertTrue(db.opens.none { it.vault == VaultKind.DECOY }) + } + + /** The set-up that was killed can be done again, and then works fully. */ + private fun DuressVaultFixture.assertSetUpCanBeRepeated() { + assertEquals(VaultUnlockResult.SUCCESS, unlockReal()) + assertEquals(DuressPinChange.SET_NEW_VAULT, security.configureDuressPin(DURESS_PIN.toCharArray())) + security.lock() + assertEquals(VaultUnlockResult.SUCCESS, security.unlockWithPin(DURESS_PIN.toCharArray())) + assertEquals(VaultKind.DECOY, db.open) + assertTrue(security.isDecoySession()) + } + + // --- the first duress PIN ------------------------------------------------------------- + + @Test + fun killedInsideOnNewVaultLeavesNoDuressPin() { + val vault = DuressVaultFixture() + assertEquals(VaultUnlockResult.SUCCESS, vault.security.unlockWithPin(PIN.toCharArray())) + vault.db.beforeWipeIfClosed = { throw ProcessDeath() } + + assertThrows(ProcessDeath::class.java) { vault.security.configureDuressPin(DURESS_PIN.toCharArray()) } + vault.restart() + vault.db.beforeWipeIfClosed = null + + vault.assertRealVaultOpensWithItsOwnKey() + assertFalse(vault.security.hasDuressPin()) + vault.assertDuressPinIsJustWrong() + vault.assertSetUpCanBeRepeated() + } + + @Test + fun killedBeforeTheSlotWasRenamedLeavesNoDuressPin() { + val vault = DuressVaultFixture() + assertEquals(VaultUnlockResult.SUCCESS, vault.security.unlockWithPin(PIN.toCharArray())) + vault.store.beforeRename = { throw ProcessDeath() } + + assertThrows(ProcessDeath::class.java) { vault.security.configureDuressPin(DURESS_PIN.toCharArray()) } + vault.restart() + + vault.assertRealVaultOpensWithItsOwnKey() + assertFalse(vault.security.hasDuressPin()) + vault.assertDuressPinIsJustWrong() + vault.assertSetUpCanBeRepeated() + } + + @Test + fun aWriteThatFailsWithAnIoErrorLeavesNoDuressPinInTheSameProcessToo() { + val vault = DuressVaultFixture() + assertEquals(VaultUnlockResult.SUCCESS, vault.security.unlockWithPin(PIN.toCharArray())) + vault.store.beforeRename = { throw IOException("disk full") } + + assertEquals(DuressPinChange.FAILED, vault.security.configureDuressPin(DURESS_PIN.toCharArray())) + vault.store.beforeRename = null + + assertFalse(vault.security.hasDuressPin()) + vault.assertDuressPinIsJustWrong() + vault.assertRealVaultOpensWithItsOwnKey() + vault.assertSetUpCanBeRepeated() + } + + @Test + fun killedAfterTheSlotWasWrittenTheDuressPinOpensTheDecoyVaultFully() { + val vault = DuressVaultFixture() + assertEquals(VaultUnlockResult.SUCCESS, vault.security.unlockWithPin(PIN.toCharArray())) + assertEquals(DuressPinChange.SET_NEW_VAULT, vault.security.configureDuressPin(DURESS_PIN.toCharArray())) + // The process dies here: no decoy database exists yet, it is made by the first duress unlock. + assertFalse(VaultKind.DECOY in vault.db.files) + vault.restart() + + vault.assertRealVaultOpensWithItsOwnKey() + assertTrue(vault.security.hasDuressPin()) + vault.security.lock() + assertEquals(VaultUnlockResult.SUCCESS, vault.security.unlockWithPin(DURESS_PIN.toCharArray())) + assertTrue(vault.security.isDecoySession()) + assertEquals(VaultKind.DECOY, vault.db.open) + assertTrue("made on the first unlock", vault.db.opens.last().allowCreate) + assertNotEquals("its own key", vault.bootstrap.toList(), vault.db.opens.last().key) + } + + @Test + fun aDecoyDatabaseThatStoppedHalfWayIsOpenedWithTheSameKeyOnTheNextTry() { + val vault = DuressVaultFixture(withDuressPin = true) + vault.db.failNextCreate = true + + assertEquals(VaultUnlockResult.DB_ERROR, vault.security.unlockWithPin(DURESS_PIN.toCharArray())) + val firstKey = vault.db.opens.last().key + assertFalse(vault.security.isDatabaseUnlocked()) + assertFalse("no fall back to the real vault", vault.db.opens.any { it.vault == VaultKind.PRIMARY }) + vault.restart() + + // The real vault is untouched, and the next duress unlock opens the file that is there. + vault.assertRealVaultOpensWithItsOwnKey() + vault.security.lock() + assertEquals(VaultUnlockResult.SUCCESS, vault.security.unlockWithPin(DURESS_PIN.toCharArray())) + assertFalse("the file is there now", vault.db.opens.last().allowCreate) + assertEquals("the same decoy key", firstKey, vault.db.opens.last().key) + assertTrue(vault.security.isDecoySession()) + } + + // --- changing an existing duress PIN -------------------------------------------------- + + private fun DuressVaultFixture.decoyKeyOfFirstUnlock(): List { + assertEquals(VaultUnlockResult.SUCCESS, security.unlockWithPin(DURESS_PIN.toCharArray())) + val key = db.opens.last().key + security.lock() + return key + } + + @Test + fun changingTheDuressPinKilledBeforeTheRenameKeepsTheOldOneAndTheSameDecoyVault() { + val vault = DuressVaultFixture(withDuressPin = true) + val decoyKey = vault.decoyKeyOfFirstUnlock() + assertEquals(VaultUnlockResult.SUCCESS, vault.security.unlockWithPin(PIN.toCharArray())) + vault.store.beforeRename = { throw ProcessDeath() } + + assertThrows(ProcessDeath::class.java) { vault.security.configureDuressPin(OTHER_DURESS_PIN.toCharArray()) } + vault.restart() + + vault.assertRealVaultOpensWithItsOwnKey() + vault.security.lock() + assertEquals(VaultUnlockResult.INVALID_CREDENTIAL, vault.security.unlockWithPin(OTHER_DURESS_PIN.toCharArray())) + assertEquals(VaultUnlockResult.SUCCESS, vault.security.unlockWithPin(DURESS_PIN.toCharArray())) + assertEquals("the same decoy vault", decoyKey, vault.db.opens.last().key) + } + + @Test + fun changingTheDuressPinKilledAfterTheRenameOpensTheSameDecoyVaultWithTheNewPinOnly() { + val vault = DuressVaultFixture(withDuressPin = true) + val decoyKey = vault.decoyKeyOfFirstUnlock() + assertEquals(VaultUnlockResult.SUCCESS, vault.security.unlockWithPin(PIN.toCharArray())) + assertEquals(DuressPinChange.SET, vault.security.configureDuressPin(OTHER_DURESS_PIN.toCharArray())) + vault.restart() + + vault.assertRealVaultOpensWithItsOwnKey() + vault.security.lock() + assertEquals(VaultUnlockResult.INVALID_CREDENTIAL, vault.security.unlockWithPin(DURESS_PIN.toCharArray())) + assertEquals(VaultUnlockResult.SUCCESS, vault.security.unlockWithPin(OTHER_DURESS_PIN.toCharArray())) + assertEquals(decoyKey, vault.db.opens.last().key) + } + + @Test + fun anOrphanedDecoyDatabaseOfARemovedDuressPinIsReplacedBySettingItAgain() { + // Turning the duress PIN off forgets the key first and deletes the file second; a kill in between + // leaves a file nothing can open. It is no half state: the PIN is plainly wrong, the real vault + // opens, and the next set-up deletes the leftover and starts a new, empty decoy vault. + val vault = DuressVaultFixture(withDuressPin = true) + val oldKey = vault.decoyKeyOfFirstUnlock() + assertTrue(VaultKind.DECOY in vault.db.files) + assertEquals(VaultUnlockResult.SUCCESS, vault.security.unlockWithPin(PIN.toCharArray())) + vault.db.beforeWipeIfClosed = { throw ProcessDeath() } + + assertThrows(ProcessDeath::class.java) { vault.security.removeDuressPin() } + vault.restart() + vault.db.beforeWipeIfClosed = null + + assertTrue("the file is left", VaultKind.DECOY in vault.db.files) + vault.assertRealVaultOpensWithItsOwnKey() + assertFalse(vault.security.hasDuressPin()) + vault.security.lock() + assertEquals(VaultUnlockResult.INVALID_CREDENTIAL, vault.security.unlockWithPin(DURESS_PIN.toCharArray())) + + assertEquals(VaultUnlockResult.SUCCESS, vault.unlockReal()) + assertEquals(DuressPinChange.SET_NEW_VAULT, vault.security.configureDuressPin(DURESS_PIN.toCharArray())) + assertFalse("the leftover went", VaultKind.DECOY in vault.db.files) + vault.security.lock() + assertEquals(VaultUnlockResult.SUCCESS, vault.security.unlockWithPin(DURESS_PIN.toCharArray())) + assertNotEquals("a new decoy vault", oldKey, vault.db.opens.last().key) + } +} diff --git a/core/security/src/jvmAndAndroidTest/kotlin/com/pasich/encly/core/security/SessionLockManagerTest.kt b/core/security/src/jvmAndAndroidTest/kotlin/com/pasich/encly/core/security/SessionLockManagerTest.kt index 7ec6069f..cc720b7a 100644 --- a/core/security/src/jvmAndAndroidTest/kotlin/com/pasich/encly/core/security/SessionLockManagerTest.kt +++ b/core/security/src/jvmAndAndroidTest/kotlin/com/pasich/encly/core/security/SessionLockManagerTest.kt @@ -1,6 +1,7 @@ package com.pasich.encly.core.security import androidx.lifecycle.LifecycleOwner +import com.pasich.encly.testutil.InMemoryKeyValueStore import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertNull @@ -8,6 +9,7 @@ import org.junit.Assert.assertThrows import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test +import org.mockito.Mockito.clearInvocations import org.mockito.Mockito.doThrow import org.mockito.Mockito.mock import org.mockito.Mockito.never @@ -179,10 +181,12 @@ class SessionLockManagerTest { private var now = 0L private var pendingTimer: (() -> Unit)? = null + private var timerDelay = -1L private fun withFakeTime() { manager.clock = { now } - manager.timer = { _, action -> + manager.timer = { delay, action -> + timerDelay = delay pendingTimer = action val cancel: () -> Unit = { pendingTimer = null } cancel @@ -487,6 +491,172 @@ class SessionLockManagerTest { assertTrue(manager.locked.value) } + // --- the 15 and 30 minute delays: process death, the alarm, the device lock ------------ + + private val longDelays = listOf(AutoLockDelay.MINUTES_15, AutoLockDelay.MINUTES_30) + + /** Runs [check] once for each long delay, on a manager of its own and with the mock's calls forgotten. */ + private fun forEachLongDelay(check: (AutoLockDelay) -> Unit) = longDelays.forEach { delay -> + clearInvocations(security) + now = 0L + pendingTimer = null + watcher.locked = false + watcher.screenOn = true + withDelay(delay.millis) + check(delay) + } + + @Test + fun theTimerIsSetForExactlyTheLongDelay() = forEachLongDelay { delay -> + manager.onStop(owner) + + assertEquals(delay.millis, timerDelay) + assertTrue(watcher.watching) + verify(security, never()).lock() + } + + @Test + fun aMillisecondBeforeTheLongDelayTheVaultIsStillOpenOnReturn() = forEachLongDelay { delay -> + manager.onStop(owner) + now += delay.millis - 1 + manager.onStart(owner) + + verify(security, never()).lock() + assertFalse(manager.locked.value) + assertNull("the alarm is cancelled on return", pendingTimer) + } + + @Test + fun atTheLongDelayTheVaultLocksOnReturnEvenIfTheAlarmNeverFired() = forEachLongDelay { delay -> + manager.onStop(owner) + now += delay.millis + manager.onStart(owner) + + verify(security).lock() + assertTrue(manager.locked.value) + } + + @Test + fun theAlarmFiringInTheBackgroundLocksTheVaultAtOnce() = forEachLongDelay { _ -> + manager.onStop(owner) + pendingTimer!!.invoke() + + verify(security).lock() + assertTrue(manager.locked.value) + assertFalse(watcher.watching) + } + + @Test + fun anAlarmThatFiresAfterTheUserCameBackInTimeDoesNothing() = forEachLongDelay { delay -> + manager.onStop(owner) + val alarm = pendingTimer!! + now += delay.millis / 2 + manager.onStart(owner) + + alarm.invoke() // the system delivers an alarm that was cancelled a moment too late + + verify(security, never()).lock() + assertFalse(manager.locked.value) + } + + @Test + fun theKeyguardComingUpWhileAwayLocksOnReturnWellInsideTheLongDelay() = forEachLongDelay { delay -> + manager.onStop(owner) + now += delay.millis / 3 + watcher.locked = true + manager.onStart(owner) + + verify(security).lock() + assertTrue(manager.locked.value) + } + + @Test + fun theScreenTurningOffWhileAwayLocksAtOnceAndTheAlarmThatFollowsDoesNothingMore() = forEachLongDelay { _ -> + manager.onStop(owner) + val alarm = pendingTimer!! + + watcher.screenOff() + + verify(security).lock() + assertTrue(manager.locked.value) + assertFalse(watcher.watching) + assertNull("the alarm is cancelled", pendingTimer) + + alarm.invoke() + verify(security, times(1)).lock() + } + + @Test + fun aScreenAlreadyOffOrAKeyguardAlreadyUpAtStopLocksAtOnceWithoutWaitingTheLongDelay() = forEachLongDelay { _ -> + watcher.screenOn = false + manager.onStop(owner) + verify(security).lock() + assertNull("no alarm was set", pendingTimer) + + clearInvocations(security) + watcher.screenOn = true + watcher.locked = true + manager.onStart(owner) + manager.onStop(owner) + verify(security).lock() + } + + @Test + fun afterProcessDeathTheStoredLongDelayIsTheOneTheTimerUses() { + longDelays.forEach { delay -> + val prefs = InMemoryKeyValueStore() + AutoLock(prefs).setDelay(delay) // chosen in the process that died + + val restoredSecurity = mock(SecurityManager::class.java) + `when`(restoredSecurity.isLockable()).thenReturn(true) + val restored = SessionLockManager(restoredSecurity, watcher, autoLock = AutoLock(prefs)) + restored.onStart(owner) + restored.clock = { now } + var scheduled = -1L + restored.timer = { delayMs, _ -> + scheduled = delayMs + ({}) + } + restored.requireUnlock() // startup finds a committed vault that is not open + assertTrue(restored.locked.value) + `when`(restoredSecurity.isDatabaseUnlocked()).thenReturn(true) + assertTrue(restored.onUnlocked()) + + restored.onStop(owner) + + assertEquals(delay.millis, scheduled) + verify(restoredSecurity, never()).lock() + } + } + + @Test + fun aProcessKilledWhileAwayInsideTheLongDelayRestartsLockedAndStaysLockedUntilAnUnlock() { + longDelays.forEach { delay -> + // The old process: the vault is open and the app went to the background. + val prefs = InMemoryKeyValueStore() + AutoLock(prefs).setDelay(delay) + val oldSecurity = mock(SecurityManager::class.java) + `when`(oldSecurity.isLockable()).thenReturn(true) + `when`(oldSecurity.isDatabaseUnlocked()).thenReturn(true) + val old = SessionLockManager(oldSecurity, watcher, autoLock = AutoLock(prefs)) + old.onStart(owner) + old.timer = { _, _ -> ({}) } + old.onStop(owner) + // The system kills the process here: nothing of the open vault, the session or the timer survives. + + val newSecurity = mock(SecurityManager::class.java) + `when`(newSecurity.isLockable()).thenReturn(true) + `when`(newSecurity.isDatabaseUnlocked()).thenReturn(false) + val restored = SessionLockManager(newSecurity, watcher, autoLock = AutoLock(prefs)) + restored.requireUnlock() + restored.onStart(owner) // the user comes back, with no suspension to resume + + assertTrue("the lock screen comes first", restored.locked.value) + verify(newSecurity, never()).lock() // there is nothing open to close + assertEquals(delay.millis, AutoLock(prefs).delayMillis) + } + } + // --- the screenshot allowance ends with every lock ------------------------------------ @Test diff --git a/core/security/src/jvmAndAndroidTest/kotlin/com/pasich/encly/core/security/UnlockInterruptedByOsLockTest.kt b/core/security/src/jvmAndAndroidTest/kotlin/com/pasich/encly/core/security/UnlockInterruptedByOsLockTest.kt new file mode 100644 index 00000000..de1389b9 --- /dev/null +++ b/core/security/src/jvmAndAndroidTest/kotlin/com/pasich/encly/core/security/UnlockInterruptedByOsLockTest.kt @@ -0,0 +1,179 @@ +package com.pasich.encly.core.security + +import androidx.lifecycle.LifecycleOwner +import com.pasich.encly.testutil.DuressVaultFixture +import com.pasich.encly.testutil.DuressVaultFixture.Companion.DURESS_PIN +import com.pasich.encly.testutil.DuressVaultFixture.Companion.PIN +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.mockito.Mockito.mock + +/** + * An unlock (PIN check, then opening the database, then publishing) that an OS lock interrupts + * (issue #131): the screen turning off, the lock key, the keyguard. Real [SecurityManager] and + * [SessionLockManager] over a fake database; the PIN is the real one and the duress one in turn. + * The app must end locked with no vault open (and no decoy session left), and the next unlock + * must work. + */ +class UnlockInterruptedByOsLockTest { + private val owner = mock(LifecycleOwner::class.java) + private val deviceLock = FakeDeviceLock() + private lateinit var vault: DuressVaultFixture + private lateinit var manager: SessionLockManager + + @Before + fun setUp() { + vault = DuressVaultFixture(withDuressPin = true) + manager = SessionLockManager(vault.security, deviceLock = deviceLock) + manager.requireUnlock() + manager.onStart(owner) + } + + private val pins = listOf(PIN to VaultKind.PRIMARY, DURESS_PIN to VaultKind.DECOY) + + /** Checks the PIN and opens the database, as the lock screen's unlock does before it publishes. */ + private fun check(pin: String) = vault.security.unlockWithPin(pin.toCharArray()) + + private fun assertLockedWithNothingOpen() { + assertTrue(manager.locked.value) + assertFalse(vault.security.isDatabaseUnlocked()) + assertNull(vault.db.open) + assertFalse(vault.security.isDecoySession()) + } + + private fun assertNextUnlockWorks(pin: String, kind: VaultKind) { + val started = manager.lockRequests() + assertEquals(VaultUnlockResult.SUCCESS, check(pin)) + assertTrue(manager.onUnlocked(started)) + assertFalse(manager.locked.value) + assertEquals(kind, vault.db.open) + assertEquals(kind == VaultKind.DECOY, vault.security.isDecoySession()) + } + + @Test + fun anOsLockRequestedBeforeTheDatabaseOpenedKeepsTheAppLocked() { + pins.forEach { (pin, kind) -> + val started = manager.lockRequests() + manager.lockNow() // nothing is open yet: it can only be counted + assertEquals(VaultUnlockResult.SUCCESS, check(pin)) + + assertFalse(manager.onUnlocked(started)) + + assertLockedWithNothingOpen() + assertNextUnlockWorks(pin, kind) + vault.security.lock() + } + } + + @Test + fun anOsLockRequestedAfterTheDatabaseOpenedClosesItBeforeTheUnlockIsPublished() { + pins.forEach { (pin, kind) -> + val started = manager.lockRequests() + assertEquals(VaultUnlockResult.SUCCESS, check(pin)) + manager.lockNow() // the vault is open now: it is closed + + assertTrue(vault.db.open == null) + assertFalse(manager.onUnlocked(started)) + + assertLockedWithNothingOpen() + assertNextUnlockWorks(pin, kind) + vault.security.lock() + } + } + + @Test + fun theKeyguardComingUpDuringTheCheckKeepsTheAppLocked() { + pins.forEach { (pin, kind) -> + val started = manager.lockRequests() + assertEquals(VaultUnlockResult.SUCCESS, check(pin)) + deviceLock.locked = true + + assertFalse(manager.onUnlocked(started)) + assertTrue(manager.isDeviceLocked()) + + assertLockedWithNothingOpen() + deviceLock.locked = false + assertNextUnlockWorks(pin, kind) + vault.security.lock() + } + } + + @Test + fun theScreenTurningOffDuringTheCheckKeepsTheAppLockedWhileItStaysOff() { + pins.forEach { (pin, kind) -> + val started = manager.lockRequests() + deviceLock.screenOn = false + manager.onStop(owner) // the activity stops with the screen off; nothing is open to close + assertEquals(VaultUnlockResult.SUCCESS, check(pin)) + + assertFalse(manager.onUnlocked(started)) + + assertLockedWithNothingOpen() + deviceLock.screenOn = true + manager.onStart(owner) + assertNextUnlockWorks(pin, kind) + vault.security.lock() + } + } + + @Test + fun theScreenGoingOffAndOnDuringTheCheckWithAnInsecureKeyguardKeepsTheAppLocked() { + pins.forEach { (pin, kind) -> + val started = manager.lockRequests() + deviceLock.screenOn = false + manager.onStop(owner) // nothing is open yet; the lock request must still be counted + deviceLock.screenOn = true // an insecure keyguard: isDeviceLocked() stays false + manager.onStart(owner) + assertFalse(deviceLock.isDeviceLocked()) + assertEquals(VaultUnlockResult.SUCCESS, check(pin)) + + assertFalse(manager.onUnlocked(started)) + + assertLockedWithNothingOpen() + assertNextUnlockWorks(pin, kind) + vault.security.lock() + } + } + + @Test + fun aBackgroundStopDuringTheCheckKeepsTheAppLocked() { + pins.forEach { (pin, kind) -> + val started = manager.lockRequests() + manager.onStop(owner) + assertEquals(VaultUnlockResult.SUCCESS, check(pin)) + + assertFalse(manager.onUnlocked(started)) + + assertLockedWithNothingOpen() + manager.onStart(owner) + assertNextUnlockWorks(pin, kind) + vault.security.lock() + } + } + + @Test + fun aRealUnlockInterruptedAfterADecoyOneStillOpensTheRealVaultNotTheDecoyOne() { + val started = manager.lockRequests() + assertEquals(VaultUnlockResult.SUCCESS, check(DURESS_PIN)) + manager.lockNow() + assertFalse(manager.onUnlocked(started)) + assertLockedWithNothingOpen() + + assertNextUnlockWorks(PIN, VaultKind.PRIMARY) + } + + private class FakeDeviceLock : DeviceLockWatcher { + var locked = false + var screenOn = true + + override fun isDeviceLocked(): Boolean = locked + + override fun isScreenOn(): Boolean = screenOn + + override fun watchScreenOff(onScreenOff: () -> Unit): () -> Unit = {} + } +} diff --git a/core/security/src/jvmAndAndroidTest/kotlin/com/pasich/encly/testutil/DuressVaultFixture.kt b/core/security/src/jvmAndAndroidTest/kotlin/com/pasich/encly/testutil/DuressVaultFixture.kt new file mode 100644 index 00000000..2cf0f588 --- /dev/null +++ b/core/security/src/jvmAndAndroidTest/kotlin/com/pasich/encly/testutil/DuressVaultFixture.kt @@ -0,0 +1,132 @@ +package com.pasich.encly.testutil + +import com.pasich.encly.core.backup.BackupFlags +import com.pasich.encly.core.security.AuthenticationManager +import com.pasich.encly.core.security.BiometricManager +import com.pasich.encly.core.security.DuressPinChange +import com.pasich.encly.core.security.SecurityManager +import com.pasich.encly.core.security.SeedPhraseManager +import com.pasich.encly.core.security.VaultDatabase +import com.pasich.encly.core.security.VaultKind +import com.pasich.encly.core.security.VaultStore +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.mockito.Mockito.mock + +/** + * A [VaultDatabase] that remembers what a real one would: which file exists, which one is open and + * under which key. [failNextCreate] leaves the file behind and fails, like a creation that stopped + * half way; [beforeWipeIfClosed] runs first in [wipeIfClosed] (a place to "kill the process"). + */ +internal class FakeVaultDatabase : VaultDatabase { + class Open(val vault: VaultKind, val allowCreate: Boolean, val key: List) + + val files = mutableSetOf() + var open: VaultKind? = null + private set + private var openKey: List? = null + val opens = mutableListOf() + var failNextCreate = false + var beforeWipeIfClosed: (() -> Unit)? = null + + override fun isDatabaseUnlocked(): Boolean = open != null + + override fun hasEncryptedDatabase(vault: VaultKind): Boolean = vault in files + + override fun unlockDatabase(dek: ByteArray, allowCreate: Boolean): Boolean = + unlockDatabase(dek, allowCreate, VaultKind.PRIMARY) + + override fun unlockDatabase(dek: ByteArray, allowCreate: Boolean, vault: VaultKind): Boolean { + val key = dek.toList() + opens += Open(vault, allowCreate, key) + if (open != null) return open == vault && openKey == key + if (vault !in files) { + if (!allowCreate) return false + files += vault + if (failNextCreate) { + failNextCreate = false + return false + } + } + open = vault + openKey = key + return true + } + + override fun reset() { + open = null + openKey = null + } + + override fun wipe() { + reset() + files.clear() + } + + override fun wipeIfClosed(only: VaultKind?): Boolean { + beforeWipeIfClosed?.invoke() + if (open != null && (only == null || open == only)) return false + if (only == null) files.clear() else files -= only + return true + } +} + +/** + * A committed vault (a recovery phrase, the PIN [PIN], onboarding done) over a real state file, a + * fake database and a fake Keystore, and "processes" over it: [restart] builds a new + * [SecurityManager] over the same file, flags and Keystore, with nothing in memory. + */ +internal class DuressVaultFixture(withDuressPin: Boolean = false) { + val file = tempVaultFile() + val factor = FakePinFactor() + val clock = FakeLockoutClock() + val prefs = InMemoryKeyValueStore() + val db = FakeVaultDatabase() + val bootstrap: ByteArray + var store: VaultStore = VaultStore(file) + private set + var security: SecurityManager + private set + + init { + val seed = SeedPhraseManager(store) + val auth = AuthenticationManager(store, factor, clock) + assertTrue(seed.initializeVault(seed.generateMnemonic())) + bootstrap = seed.copyBootstrapKey()!! + assertTrue(auth.configurePin(PIN.toCharArray(), bootstrap)) + if (withDuressPin) { + assertEquals( + DuressPinChange.SET_NEW_VAULT, + auth.configureDuressPin(DURESS_PIN.toCharArray(), bootstrap) { true }, + ) + } + db.files += VaultKind.PRIMARY + prefs.commit { + putBoolean("onboarding_shown_v3", true) + putLong(BackupFlags.LAST_EXPORT_KEY, 1L) + } + security = newSecurity(store) + } + + /** A new process: the memory is gone, the state file, the flags, the Keystore and the files stay. */ + fun restart(): SecurityManager { + store = VaultStore(file) + security = newSecurity(store) + return security + } + + private fun newSecurity(vaultStore: VaultStore): SecurityManager = SecurityManager( + prefs, + vaultStore, + SeedPhraseManager(vaultStore), + db, + AuthenticationManager(vaultStore, factor, clock), + mock(BiometricManager::class.java), + ) {} + + companion object { + const val PIN = "135790" + const val DURESS_PIN = "975310" + const val OTHER_DURESS_PIN = "112358" + } +} diff --git a/shared/src/androidHostTest/kotlin/com/pasich/encly/ui/screens/TestApp.kt b/shared/src/androidHostTest/kotlin/com/pasich/encly/ui/screens/TestApp.kt index a4972a7f..40a9d9dc 100644 --- a/shared/src/androidHostTest/kotlin/com/pasich/encly/ui/screens/TestApp.kt +++ b/shared/src/androidHostTest/kotlin/com/pasich/encly/ui/screens/TestApp.kt @@ -215,7 +215,7 @@ internal class TestApp { /** The start-up work of the home screen, with the trash and the version notes the tests control. */ fun startup(tracker: WhatsNewTracker = freshInstall()) = StartupViewModel( tracker, - PurgeExpiredTrashUseCase(notes, InMemoryKeyValueStore()), + PurgeExpiredTrashUseCase(notes, InMemoryKeyValueStore(), mock(SecurityManager::class.java)), notes, ) diff --git a/shared/src/commonMain/kotlin/com/pasich/encly/domain/usecase/note/PurgeExpiredTrashUseCase.kt b/shared/src/commonMain/kotlin/com/pasich/encly/domain/usecase/note/PurgeExpiredTrashUseCase.kt index 90854744..c728098f 100644 --- a/shared/src/commonMain/kotlin/com/pasich/encly/domain/usecase/note/PurgeExpiredTrashUseCase.kt +++ b/shared/src/commonMain/kotlin/com/pasich/encly/domain/usecase/note/PurgeExpiredTrashUseCase.kt @@ -3,6 +3,7 @@ package com.pasich.encly.domain.usecase.note import com.pasich.encly.core.AppLogger import com.pasich.encly.core.common.currentTimeMillis import com.pasich.encly.core.platform.KeyValueStore +import com.pasich.encly.core.security.SecurityManager import com.pasich.encly.domain.repository.NotesRepository import dev.zacsweers.metro.Inject @@ -15,6 +16,9 @@ private const val MILLIS_PER_DAY = 24L * 60 * 60 * 1000 private const val MAX_ADVANCE_MILLIS = 2 * MILLIS_PER_DAY private const val LAST_PURGE_KEY = "trash_last_purge_at" + +/** The decoy vault's own purge time; written only after a duress unlock purged, so it is no trace of its own. */ +private const val DECOY_LAST_PURGE_KEY = "trash_last_purge_at_d" private const val TAG = "PurgeExpiredTrash" /** How long, in milliseconds, a note stays in the trash. */ @@ -29,27 +33,42 @@ const val TRASH_RETENTION_MILLIS = TRASH_RETENTION_DAYS * MILLIS_PER_DAY * The wall clock is not trusted: the time of the last purge is kept in [flags], and one purge measures from at most two * days after it, so a clock set far forward deletes the trash two days further per unlock, not all of it at once. A * clock that went back before the last purge skips the purge until it catches up. + * + * Each vault has its own purge time (the decoy vault's is [DECOY_LAST_PURGE_KEY]): one shared by both would let + * unlocks of the decoy vault with a forward clock use up the allowance of the real one. */ @Inject -class PurgeExpiredTrashUseCase(private val repository: NotesRepository, private val flags: KeyValueStore) { +class PurgeExpiredTrashUseCase( + private val repository: NotesRepository, + private val flags: KeyValueStore, + private val securityManager: SecurityManager, +) { /** The number of notes deleted. [now] is the time to measure from. */ suspend operator fun invoke(now: Long = currentTimeMillis()): Result { - val last = flags.getLong(LAST_PURGE_KEY, NEVER) + // Read once: a purge that straddles a vault switch fails in the repository and records nothing. + val decoy = securityManager.isDecoySession() + val last = if (decoy) flags.getLong(DECOY_LAST_PURGE_KEY, NEVER) else flags.getLong(LAST_PURGE_KEY, NEVER) return if (last != NEVER && now < last) { AppLogger.w(TAG, "Clock is behind the last purge, skipped") Result.success(0) } else { // No purge before: measure from now. Else from now, but no further than two days past the last purge. - purge(now, measuredFrom = if (last == NEVER) now else minOf(now, last + MAX_ADVANCE_MILLIS)) + purge(now, decoy, measuredFrom = if (last == NEVER) now else minOf(now, last + MAX_ADVANCE_MILLIS)) } } - private suspend fun purge(now: Long, measuredFrom: Long): Result = + private suspend fun purge(now: Long, decoy: Boolean, measuredFrom: Long): Result = // A trashed note without a time (imported, restored from a backup) starts its 28 days now. repository.stampUntimedTrash(now).mapCatching { // Expired means older than the retention, so a trash time after `now` is never below the cutoff. repository.deleteTrashedBefore(measuredFrom - TRASH_RETENTION_MILLIS).getOrThrow() - }.onSuccess { flags.edit { putLong(LAST_PURGE_KEY, measuredFrom) } } + }.onSuccess { + if (decoy) { + flags.edit { putLong(DECOY_LAST_PURGE_KEY, measuredFrom) } + } else { + flags.edit { putLong(LAST_PURGE_KEY, measuredFrom) } + } + } } private const val NEVER = 0L diff --git a/shared/src/jvmAndAndroidTest/kotlin/com/pasich/encly/data/repository/VaultSwitchLateWriteTest.kt b/shared/src/jvmAndAndroidTest/kotlin/com/pasich/encly/data/repository/VaultSwitchLateWriteTest.kt new file mode 100644 index 00000000..852f5b30 --- /dev/null +++ b/shared/src/jvmAndAndroidTest/kotlin/com/pasich/encly/data/repository/VaultSwitchLateWriteTest.kt @@ -0,0 +1,241 @@ +package com.pasich.encly.data.repository + +import com.pasich.encly.core.security.SecurityManager +import com.pasich.encly.data.backup.RoomVaultDataStore +import com.pasich.encly.data.database.AppDatabase +import com.pasich.encly.data.database.DatabaseLease +import com.pasich.encly.data.database.DatabasePlatform +import com.pasich.encly.data.database.SecureDatabaseManager +import com.pasich.encly.data.database.VaultFile +import com.pasich.encly.data.database.dao.BackupDao +import com.pasich.encly.data.database.dao.NotesDao +import com.pasich.encly.data.database.dao.TagsDao +import com.pasich.encly.data.database.dao.TasksDao +import com.pasich.encly.data.model.Note +import com.pasich.encly.data.model.Tag +import com.pasich.encly.data.model.Task +import com.pasich.encly.domain.usecase.note.PurgeExpiredTrashUseCase +import com.pasich.encly.testutil.InMemoryKeyValueStore +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.async +import kotlinx.coroutines.runBlocking +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotSame +import org.junit.Assert.assertTrue +import org.junit.Test +import org.mockito.Mockito.mock +import org.mockito.Mockito.verifyNoInteractions +import org.mockito.Mockito.`when` + +/** + * Work that was started in one vault and completes after the app switched to the other one (or + * re-locked and reopened the same one): an editor save, a backup, a trash purge (issue #131). The + * guarantee is the lease of [SecureDatabaseManager]: a repository or a data store keeps the opening it + * was created in, and every operation resolves its DAO through that lease, so a late write fails + * before it reaches any DAO of the vault that is open now. The real manager is used, with mock + * databases put in as its open one (as in its own host test, without the native cipher). + */ +class VaultSwitchLateWriteTest { + private class Vault(val file: VaultFile) { + val notes: NotesDao = mock(NotesDao::class.java) + val tags: TagsDao = mock(TagsDao::class.java) + val tasks: TasksDao = mock(TasksDao::class.java) + val backup: BackupDao = mock(BackupDao::class.java) + val database: AppDatabase = mock(AppDatabase::class.java).also { + `when`(it.notesDao()).thenReturn(notes) + `when`(it.tagsDao()).thenReturn(tags) + `when`(it.tasksDao()).thenReturn(tasks) + `when`(it.backupDao()).thenReturn(backup) + } + val key = ByteArray(32) { (if (file == VaultFile.PRIMARY) 1 else 2).toByte() } + + fun assertUntouched() { + verifyNoInteractions(notes, tags, tasks, backup) + } + } + + private val real = Vault(VaultFile.PRIMARY) + private val decoy = Vault(VaultFile.DECOY) + private val manager = SecureDatabaseManager(mock(DatabasePlatform::class.java)) + private val note = Note(id = 5, title = "t", value = "v", date = 1L) + private val base = note.copy(value = "before") + + private fun setField(name: String, value: Any?) = + SecureDatabaseManager::class.java.getDeclaredField(name).apply { isAccessible = true }.set(manager, value) + + /** The state of a manager that just opened [vault]'s database (a new lease, as every opening gets). */ + private fun open(vault: Vault) { + setField("database", vault.database) + setField("openKey", vault.key.copyOf()) + setField("openFile", vault.file) + setField("lease", DatabaseLease()) + setField("isUnlocked", true) + } + + /** What a lock, or the switch to the other PIN, does first: closes whatever is open. */ + private fun lock() = manager.reset() + + @Test + fun aRepositoryWritesIntoTheVaultItWasCreatedIn() = runBlocking { + open(decoy) + `when`(decoy.notes.insertNoteWithTags(note)).thenReturn(7L) + + assertEquals(7L, NotesRepositoryImpl(manager).insertNote(note).getOrNull()) + real.assertUntouched() + } + + @Test + fun anEditorSaveStartedInTheRealVaultAndCompletingInTheDecoyOneIsDropped() = runBlocking { + open(real) + val repository = NotesRepositoryImpl(manager) + val gate = CompletableDeferred() + val save = async { + gate.await() // the editor was still about to write when the PIN of the other vault was typed + repository.updateEdited(note, base) + } + + lock() + open(decoy) + gate.complete(Unit) + + assertTrue(save.await().isFailure) + decoy.assertUntouched() + real.assertUntouched() + } + + @Test + fun anEditorSaveStartedInTheDecoyVaultAndCompletingInTheRealOneIsDropped() = runBlocking { + open(decoy) + val repository = NotesRepositoryImpl(manager) + val gate = CompletableDeferred() + val save = async { + gate.await() + repository.insertNote(note) + } + + lock() + open(real) + gate.complete(Unit) + + assertTrue(save.await().isFailure) + real.assertUntouched() + } + + @Test + fun aWriteAfterALockThatReopenedTheSameVaultIsDroppedToo() = runBlocking { + open(real) + val repository = NotesRepositoryImpl(manager) + val lease = manager.captureLease() + + lock() + open(real) + + assertNotSame("a new opening, a new lease", lease, manager.captureLease()) + assertTrue(repository.setTrashed(note.id, true, 1_000L).isFailure) + assertTrue(repository.updateEdited(note, base).isFailure) + real.assertUntouched() + } + + @Test + fun aWriteAfterALockWithNothingReopenedIsDropped() = runBlocking { + open(real) + val repository = NotesRepositoryImpl(manager) + + lock() + + assertTrue(repository.insertNote(note).isFailure) + real.assertUntouched() + } + + @Test + fun aTrashPurgeStartedInTheRealVaultAndCompletingInTheDecoyOneDeletesNothingAndRecordsNothing() = runBlocking { + open(real) + val flags = InMemoryKeyValueStore() + val purge = PurgeExpiredTrashUseCase(NotesRepositoryImpl(manager), flags, mock(SecurityManager::class.java)) + val gate = CompletableDeferred() + val purging = async { + gate.await() + purge(now = NOW) + } + + lock() + open(decoy) + gate.complete(Unit) + + assertTrue(purging.await().isFailure) + decoy.assertUntouched() + real.assertUntouched() + assertEquals("the purge did not count as done", 0L, flags.getLong("trash_last_purge_at", 0L)) + } + + @Test + fun taskAndTagWritesOfAnEarlierOpeningAreDroppedToo() = runBlocking { + open(real) + val tasks = TasksRepositoryImpl(manager) + val tags = TagsRepositoryImpl(manager) + + lock() + open(decoy) + + assertTrue(tasks.insertTask(Task(id = 1, title = "t")).isFailure) + assertTrue(tasks.deleteTaskById(1).isFailure) + assertTrue(tags.addTag(Tag(id = 1, nameTag = "x")).isFailure) + assertTrue(tags.deleteTag(Tag(id = 1, nameTag = "x")).isFailure) + decoy.assertUntouched() + real.assertUntouched() + } + + @Test + fun aBackupBoundToTheRealVaultCanNotReadOrWriteTheDecoyOneAfterTheSwitch() = runBlocking { + open(real) + val bound = RoomVaultDataStore(manager).bindToCurrentSession() + bound.assertCurrentSession() + + lock() + open(decoy) + + assertTrue(runCatching { bound.assertCurrentSession() }.isFailure) + assertTrue(runCatching { bound.snapshot() }.isFailure) + assertTrue(runCatching { bound.deleteAll() }.isFailure) + assertTrue(runCatching { bound.insertNote(note) }.isFailure) + assertTrue(runCatching { bound.insertTag(Tag(id = 1, nameTag = "x")) }.isFailure) + decoy.assertUntouched() + real.assertUntouched() + } + + @Test + fun aBackupStartedInTheRealVaultFailsWhenItsLateStepComesAfterTheSwitch() = runBlocking { + open(real) + val bound = RoomVaultDataStore(manager).bindToCurrentSession() + val gate = CompletableDeferred() + val late = async { + gate.await() + runCatching { bound.insertNote(note) } + } + + lock() + open(decoy) + gate.complete(Unit) + + assertTrue(late.await().isFailure) + decoy.assertUntouched() + } + + @Test + fun theOtherVaultCanNotBeOpenedWhileOneIsOpenSoNoWriteCanLandInTheWrongFile() { + open(real) + val lease = manager.captureLease() + + assertFalse(manager.unlockDatabase(decoy.key, allowCreate = true, file = VaultFile.DECOY)) + assertFalse(manager.unlockDatabase(real.key, allowCreate = false, file = VaultFile.DECOY)) + + assertTrue("the open one is as it was", manager.isDatabaseUnlocked()) + assertEquals(lease, manager.captureLease()) + decoy.assertUntouched() + } + + private companion object { + const val NOW = 40L * 24 * 60 * 60 * 1000 + } +} diff --git a/shared/src/jvmAndAndroidTest/kotlin/com/pasich/encly/domain/usecase/note/TrashExpiryTest.kt b/shared/src/jvmAndAndroidTest/kotlin/com/pasich/encly/domain/usecase/note/TrashExpiryTest.kt index 8c33edbb..92dea646 100644 --- a/shared/src/jvmAndAndroidTest/kotlin/com/pasich/encly/domain/usecase/note/TrashExpiryTest.kt +++ b/shared/src/jvmAndAndroidTest/kotlin/com/pasich/encly/domain/usecase/note/TrashExpiryTest.kt @@ -1,5 +1,6 @@ package com.pasich.encly.domain.usecase.note +import com.pasich.encly.core.security.SecurityManager import com.pasich.encly.data.model.Note import com.pasich.encly.domain.repository.NotesRepository import com.pasich.encly.testutil.InMemoryKeyValueStore @@ -17,7 +18,8 @@ import org.mockito.Mockito.`when` class TrashExpiryTest { private val repository = TestNotesRepository() private val flags = InMemoryKeyValueStore() - private val purge = PurgeExpiredTrashUseCase(repository, flags) + private val security = mock(SecurityManager::class.java) + private val purge = PurgeExpiredTrashUseCase(repository, flags, security) private fun trashed(id: Long, trashedAt: Long?) = Note(id = id, isTrash = true, trashedAt = trashedAt) @@ -110,7 +112,7 @@ class TrashExpiryTest { val notes = mock(NotesRepository::class.java) `when`(notes.stampUntimedTrash(NOW)).thenReturn(Result.failure(IllegalStateException("disk"))) - assertTrue(PurgeExpiredTrashUseCase(notes, flags)(NOW).isFailure) + assertTrue(PurgeExpiredTrashUseCase(notes, flags, security)(NOW).isFailure) verify(notes, never()).deleteTrashedBefore(anyLong()) } @@ -121,7 +123,7 @@ class TrashExpiryTest { `when`(notes.deleteTrashedBefore(NOW - TRASH_RETENTION_MILLIS)) .thenReturn(Result.failure(IllegalStateException("vault locked"))) - assertTrue(PurgeExpiredTrashUseCase(notes, flags)(NOW).isFailure) + assertTrue(PurgeExpiredTrashUseCase(notes, flags, security)(NOW).isFailure) } @Test @@ -169,11 +171,48 @@ class TrashExpiryTest { `when`(notes.deleteTrashedBefore(NOW - TRASH_RETENTION_MILLIS)) .thenReturn(Result.failure(IllegalStateException("vault locked"))) - PurgeExpiredTrashUseCase(notes, flags)(NOW) + PurgeExpiredTrashUseCase(notes, flags, security)(NOW) assertEquals(0L, flags.getLong("trash_last_purge_at", 0L)) } + @Test + fun theDecoyVaultKeepsItsOwnPurgeTimeAndNeverMovesTheRealOne() = runTest { + purge(NOW) // the real vault purged once + `when`(security.isDecoySession()).thenReturn(true) + + // The decoy is unlocked again and again with the clock a year ahead: 14 times is far more than 28 days. + repeat(20) { purge(NOW + 365 * DAY) } + + assertEquals(NOW, flags.getLong("trash_last_purge_at", 0L)) + assertEquals(NOW + 365 * DAY, flags.getLong("trash_last_purge_at_d", 0L)) + `when`(security.isDecoySession()).thenReturn(false) + repository.purgeCutoffs.clear() + purge(NOW + 365 * DAY) + assertEquals( + "the real vault still advances two days at most", + listOf(NOW + 2 * DAY - TRASH_RETENTION_MILLIS), + repository.purgeCutoffs, + ) + } + + @Test + fun theRealVaultWritesNoDecoyKey() = runTest { + purge(NOW) + + assertEquals(0L, flags.getLong("trash_last_purge_at_d", 0L)) + } + + @Test + fun theDecoyVaultWritesOnlyItsOwnKeyAndOnlyWhenItPurged() = runTest { + `when`(security.isDecoySession()).thenReturn(true) + + purge(NOW) + + assertEquals(0L, flags.getLong("trash_last_purge_at", 0L)) + assertEquals(NOW, flags.getLong("trash_last_purge_at_d", 0L)) + } + private companion object { const val DAY = 24L * 60 * 60 * 1000 const val NOW = 2_000_000_000_000L diff --git a/shared/src/jvmAndAndroidTest/kotlin/com/pasich/encly/whatsnew/WhatsNewTest.kt b/shared/src/jvmAndAndroidTest/kotlin/com/pasich/encly/whatsnew/WhatsNewTest.kt index a3a4bcb0..d53fc72f 100644 --- a/shared/src/jvmAndAndroidTest/kotlin/com/pasich/encly/whatsnew/WhatsNewTest.kt +++ b/shared/src/jvmAndAndroidTest/kotlin/com/pasich/encly/whatsnew/WhatsNewTest.kt @@ -1,5 +1,6 @@ package com.pasich.encly.whatsnew +import com.pasich.encly.core.security.SecurityManager import com.pasich.encly.data.model.Note import com.pasich.encly.domain.usecase.note.CleanTrashNotesUseCase import com.pasich.encly.domain.usecase.note.PurgeExpiredTrashUseCase @@ -22,6 +23,7 @@ import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test +import org.mockito.Mockito.mock import java.io.File import java.util.Properties @@ -193,7 +195,7 @@ class WhatsNewTest { private fun startup(version: String, repository: TestNotesRepository = TestNotesRepository()) = StartupViewModel( tracker(version), - PurgeExpiredTrashUseCase(repository, flags), + PurgeExpiredTrashUseCase(repository, flags, mock(SecurityManager::class.java)), repository, )