Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 49 additions & 5 deletions app/src/main/java/com/mattintech/papercase/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -356,6 +356,17 @@ class MainActivity : AppCompatActivity() {

private fun getSessionTimeoutMs(): Long = prefs.lockerTimeoutMinutes * 60 * 1000L

/** A real unlock this session, so the locker key is usable. */
private fun hasUnlockedSession(): Boolean =
isLockerUnlocked || SessionManager.isSessionValid(getSessionTimeoutMs())

/**
* Nothing in the locker, so it opens without asking to unlock. A document waiting to be opened
* (e.g. from a reminder) means there is something after all, so that still asks.
*/
private fun opensWithoutUnlock(): Boolean =
pendingOpenDocumentId == null && lockerRepository.isKnownEmpty()

override fun onNewIntent(intent: android.content.Intent) {
super.onNewIntent(intent)
setIntent(intent)
Expand All @@ -371,11 +382,13 @@ class MainActivity : AppCompatActivity() {
pendingOpenDocumentId = id
if (isLockerUnlocked && binding.layoutLockerContent.visibility == View.VISIBLE) {
openPendingDocument()
} else if (appAlreadyOpen) {
} else if (appAlreadyOpen || binding.layoutLockerContent.visibility == View.VISIBLE) {
// (Also when a fresh start opened a seemingly empty locker without unlocking: the
// document says otherwise, so ask now)
binding.bottomNavigation.menu.findItem(R.id.nav_locker)?.isChecked = true
showLockerTab(promptIfLocked = true)
}
// On a fresh start the locker tab is already showing and asking to unlock
// On a fresh start the locker tab is otherwise already showing and asking to unlock
return
}

Expand Down Expand Up @@ -877,6 +890,12 @@ class MainActivity : AppCompatActivity() {
return
}

// Empty locker: nothing to protect yet. Adding the first document or folder asks to unlock then.
if (opensWithoutUnlock()) {
displayLockerTab()
return
}

// No biometric / screen lock on this device: nothing to unlock with
if (BiometricAuthHelper.checkBiometricAvailability(this) !is BiometricAuthHelper.BiometricStatus.Ready) {
SessionManager.markAuthenticated()
Expand All @@ -894,7 +913,11 @@ class MainActivity : AppCompatActivity() {
val popup = androidx.appcompat.widget.PopupMenu(this, anchor)
popup.menuInflater.inflate(R.menu.menu_toolbar_settings, popup.menu)
popup.setForceShowIcon(true)
popup.menu.findItem(R.id.action_lock).isEnabled = isLockerUnlocked
popup.menu.findItem(R.id.action_lock).apply {
isEnabled = isLockerUnlocked
// An empty locker is never shown locked, so there's nothing to lock
isVisible = !lockerRepository.isKnownEmpty()
}
popup.setOnMenuItemClickListener { item ->
when (item.itemId) {
R.id.action_transfer -> withLockerUnlocked("Unlock to transfer or back up") { showVaultTransferOptions() }
Expand Down Expand Up @@ -935,7 +958,8 @@ class MainActivity : AppCompatActivity() {
folders = emptyList()
lockerAdapter.submitList(emptyList())
thumbnailLoader.clear()
if (binding.layoutSecureLocker.visibility == View.VISIBLE) showLockedLocker()
if (binding.layoutSecureLocker.visibility != View.VISIBLE) return
if (opensWithoutUnlock()) displayLockerTab() else showLockedLocker()
}

private fun promptLockerUnlock() {
Expand All @@ -962,6 +986,12 @@ class MainActivity : AppCompatActivity() {
binding.fabAddDocument.show()
binding.tvToolbarTitle.text = "Locker"
applyLockerLayout()
if (!hasUnlockedSession()) {
// Empty locker shown without an unlock: the key isn't usable, and there's nothing to
// decrypt, migrate or back up yet
loadSecureLockerDocuments()
return
}
migrateLockerKeyIfNeeded()
// The locker key is usable right now: bring the automatic backup snapshot up to date
lifecycleScope.launch { AutoBackupManager.refreshIfNeeded(this@MainActivity) }
Expand Down Expand Up @@ -1010,7 +1040,9 @@ class MainActivity : AppCompatActivity() {

private fun handleLockerLocked() {
lockLockerInPlace()
Toast.makeText(this, "Locker locked. Unlock again to continue.", Toast.LENGTH_SHORT).show()
if (!lockerRepository.isKnownEmpty()) {
Toast.makeText(this, "Locker locked. Unlock again to continue.", Toast.LENGTH_SHORT).show()
}
}

private fun showLockerKeyLostDialog() {
Expand All @@ -1036,6 +1068,18 @@ class MainActivity : AppCompatActivity() {

private fun loadSecureLockerDocuments() {
lifecycleScope.launch {
if (!hasUnlockedSession() && lockerRepository.isKnownEmpty()) {
// Nothing to show, and reading the catalog would need an unlock
if (lockerRepository.isKeyLost()) {
// Android deleted the key (e.g. the screen lock was removed). Nothing was stored
// with it, so start a fresh locker instead of failing on the first save.
lockerRepository.resetAfterKeyLoss()
}
allDocuments = emptyList()
folders = emptyList()
renderLocker()
return@launch
}
allDocuments = try {
folders = lockerRepository.getFolders()
lockerRepository.getAllDocuments()
Expand Down
3 changes: 3 additions & 0 deletions app/src/main/java/com/mattintech/papercase/PapercaseApp.kt
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import com.mattintech.papercase.data.PreferencesManager
import com.mattintech.papercase.locker.backup.AutoBackupManager
import com.mattintech.papercase.locker.backup.DailyWorker
import com.mattintech.papercase.locker.reminders.ReminderNotifier
import com.mattintech.papercase.locker.repository.SecureLockerRepository

class PapercaseApp : Application() {

Expand All @@ -29,6 +30,8 @@ class PapercaseApp : Application() {
ClipboardSecurityManager.createNotificationChannel(this)
ReminderNotifier.createChannel(this)
SessionManager.init(this)
val lockerRepository = SecureLockerRepository(this)
SessionManager.isLockerEmpty = { lockerRepository.isKnownEmpty() }
DailyWorker.schedule(this)
getSharedPreferences(PreferencesManager.NAME, MODE_PRIVATE).registerOnSharedPreferenceChangeListener(settingsListener)

Expand Down
26 changes: 22 additions & 4 deletions app/src/main/java/com/mattintech/papercase/auth/SessionManager.kt
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,20 @@ object SessionManager {
}
}

/**
* Whether the locker has no documents or folders. An empty locker is never shown as locked, and
* locking it isn't announced. Set by PapercaseApp; defaults to not empty so nothing opens by mistake.
*/
var isLockerEmpty: () -> Boolean = { false }

/**
* True when the locker can be shown without asking to unlock: after a recent unlock, or when
* there's nothing in it. This doesn't make the locker key usable; saving into an empty locker
* still needs an unlock first (see [isSessionValid]).
*/
fun canShowLocker(timeoutMs: Long = DEFAULT_TIMEOUT_MS): Boolean =
isSessionValid(timeoutMs) || isLockerEmpty()

private var isInForeground: Boolean = true
private var backgroundTimestamp: Long = 0L
private var appContext: Context? = null
Expand Down Expand Up @@ -132,8 +146,7 @@ object SessionManager {
if (backgroundTimestamp > 0L) {
val elapsedInBackground = timeProvider() - backgroundTimestamp
if (lastAuthTime > 0L && elapsedInBackground >= BACKGROUND_INACTIVITY_TIMEOUT_MS) {
lock()
appContext?.let { notifyLockerLocked(it) }
lockDueToInactivity()
}
backgroundTimestamp = 0L
}
Expand Down Expand Up @@ -161,11 +174,16 @@ object SessionManager {

fun checkAndLockDueToInactivity() {
if (!isInForeground && lastAuthTime > 0L) {
lock()
appContext?.let { notifyLockerLocked(it) }
lockDueToInactivity()
}
}

/** Ends the session; only tells the user when there was something to lock away. */
private fun lockDueToInactivity() {
lock()
if (!isLockerEmpty()) appContext?.let { notifyLockerLocked(it) }
}

fun createNotificationChannel(context: Context) {
val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as? NotificationManager
?: return
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,20 @@ class SecureLockerRepository(private val context: Context) {
}
return map
}

/**
* Whether a catalog file says the locker has no documents and no folders. The flag sits next to
* the ciphertext so it can be read without the auth-bound key. Catalogs written before the flag
* existed count as not empty, so they stay locked until their next save.
*/
fun isEmptyCatalog(wrapperJson: String?): Boolean {
if (wrapperJson == null) return true
return runCatching { JSONObject(wrapperJson).optBoolean("empty", false) }.getOrDefault(false)
}

// Last emptiness read, keyed by the catalog's size and time so it's only re-read after a write
@Volatile
private var emptyCache: Triple<Long, Long, Boolean>? = null
}

private val lockerDir = File(context.filesDir, "locker").apply { if (!exists()) mkdirs() }
Expand Down Expand Up @@ -78,6 +92,26 @@ class SecureLockerRepository(private val context: Context) {
/** True once the locker has been created on this device (even if it's now empty). */
fun exists(): Boolean = catalogFile.exists()

/**
* True when the locker has no documents or folders (or doesn't exist yet), so there's nothing to
* unlock. Read without decrypting. The flag isn't authenticated, but nothing is decrypted on its
* word: a wrong flag only shows an empty list, and saving still needs the key and the real catalog.
*/
fun isKnownEmpty(): Boolean {
if (!catalogFile.exists()) return true
val length = catalogFile.length()
val modified = catalogFile.lastModified()
emptyCache?.let { (l, m, empty) -> if (l == length && m == modified) return empty }
val empty = isEmptyCatalog(runCatching { catalogFile.readText() }.getOrDefault("{}"))
emptyCache = Triple(length, modified, empty)
return empty
}

/** True when the catalog needs the auth-bound key but Android has deleted it. */
fun isKeyLost(): Boolean =
catalogKeyVersion() == LockerKeystoreHelper.KEY_VERSION_AUTH_BOUND &&
!LockerKeystoreHelper.hasKey(LockerKeystoreHelper.KEY_VERSION_AUTH_BOUND)

/** True when the locker still uses the key that works without authentication. */
fun needsAuthBoundMigration(): Boolean =
isDeviceSecure() && catalogKeyVersion() == LockerKeystoreHelper.KEY_VERSION_LEGACY
Expand Down Expand Up @@ -143,6 +177,8 @@ class SecureLockerRepository(private val context: Context) {
put("ciphertext", cipherBase64)
put("iv", ivBase64)
put("keyVersion", version)
// Readable without the key, so an empty locker can be shown without unlocking
put("empty", catalog.documents.isEmpty() && catalog.folders.isEmpty())
}
val tempFile = File(lockerDir, "catalog.enc.tmp")
tempFile.writeText(wrapper.toString())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,8 @@ class AddDocumentActivity : AppCompatActivity() {

override fun onResume() {
super.onResume()
if (!SessionManager.isLockerUnlocked) {
// An empty locker opens without unlocking, so the first document can be filled in before it
if (!SessionManager.canShowLocker()) {
finish()
}
}
Expand Down Expand Up @@ -931,6 +932,14 @@ class AddDocumentActivity : AppCompatActivity() {
val notes = binding.etNotes.text?.toString()?.trim().orEmpty()
val docType = getSelectedDocumentType()

// First document in an empty locker: nothing was unlocked yet, and the locker key needs it now
if (!SessionManager.isLockerUnlocked && SessionManager.isLockerEmpty() &&
BiometricAuthHelper.getDeviceSecurityLevel(this).isProtected
) {
unlockAndRetrySave(subtitle = "Confirm it's you to add this document to your locker.")
return
}

binding.btnSaveDocument.isEnabled = false

lifecycleScope.launch {
Expand Down Expand Up @@ -1073,11 +1082,13 @@ class AddDocumentActivity : AppCompatActivity() {
}
}

private fun unlockAndRetrySave() {
private fun unlockAndRetrySave(
subtitle: String = "The locker locked while you were editing. Your changes are kept."
) {
BiometricAuthHelper.promptGeneralUnlock(
activity = this,
title = "Unlock to save",
subtitle = "The locker locked while you were editing. Your changes are kept.",
subtitle = subtitle,
onSuccess = {
SessionManager.markAuthenticated()
validateAndSave()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -289,13 +289,33 @@ class LockerActions(
promptFolderName("New folder", "") { name ->
val folder = Folder(name = name, parentId = parentId)
// Saved before anything (like a move) uses it, so the two writes don't overlap
launch {
repository.saveFolder(folder)
onCreated(folder)
whenKeyUsable("Confirm it's you to create this folder") {
launch {
repository.saveFolder(folder)
onCreated(folder)
}
}
}
}

/**
* An empty locker is shown without unlocking, so the first folder may be created before the
* locker key is usable. Ask for fingerprint / PIN then; otherwise just carry on.
*/
private fun whenKeyUsable(subtitle: String, action: () -> Unit) {
if (SessionManager.isLockerUnlocked || !BiometricAuthHelper.getDeviceSecurityLevel(activity).isProtected) return action()
BiometricAuthHelper.promptGeneralUnlock(
activity = activity,
title = "Unlock Locker",
subtitle = subtitle,
onSuccess = {
SessionManager.markAuthenticated()
action()
},
onError = { _, _ -> }
)
}

private fun promptFolderName(title: String, initial: String, onName: (String) -> Unit) {
val input = DialogInput(activity, hint = "Folder name")
input.editText.setText(initial)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ class CropActivity : AppCompatActivity() {

override fun onResume() {
super.onResume()
if (!SessionManager.isLockerUnlocked) finish()
if (!SessionManager.canShowLocker()) finish()
}

private fun finishWith(bitmap: Bitmap?) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package com.mattintech.papercase.auth

import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.After
import org.junit.Before
import org.junit.Test

Expand All @@ -14,6 +15,12 @@ class SessionManagerTest {
fakeCurrentTime = 100_000L
SessionManager.timeProvider = { fakeCurrentTime }
SessionManager.lock()
SessionManager.isLockerEmpty = { false }
}

@After
fun tearDown() {
SessionManager.isLockerEmpty = { false }
}

@Test
Expand Down Expand Up @@ -111,4 +118,49 @@ class SessionManagerTest {
SessionManager.keepAlive()
assertFalse(SessionManager.isSessionValid())
}

@Test
fun testLockedLockerWithDocuments_cannotBeShown() {
assertFalse(SessionManager.canShowLocker())
}

@Test
fun testEmptyLocker_canBeShownWithoutUnlock() {
SessionManager.isLockerEmpty = { true }
assertTrue(SessionManager.canShowLocker())
// Showing it doesn't count as an unlock: saving into it still has to ask
assertFalse(SessionManager.isSessionValid())
}

@Test
fun testEmptyLocker_staysShowableAfterBackgroundTimeout() {
SessionManager.isLockerEmpty = { true }
SessionManager.markAuthenticated()
SessionManager.onAppEnteredBackground()
fakeCurrentTime += 31_000L
SessionManager.onAppEnteredForeground()
assertFalse("Session still ends", SessionManager.isLockerUnlocked)
assertTrue("Empty locker isn't shown locked", SessionManager.canShowLocker())
}

@Test
fun testFirstDocumentAdded_locksAgainAfterBackgroundTimeout() {
var empty = true
SessionManager.isLockerEmpty = { empty }
SessionManager.markAuthenticated()
empty = false
SessionManager.onAppEnteredBackground()
fakeCurrentTime += 31_000L
SessionManager.onAppEnteredForeground()
assertFalse(SessionManager.canShowLocker())
}

@Test
fun testEmptyLocker_validSessionStillExpires() {
SessionManager.isLockerEmpty = { true }
SessionManager.markAuthenticated()
fakeCurrentTime += SessionManager.MAX_AUTH_AGE_MS + 1
assertFalse(SessionManager.isSessionValid())
assertTrue(SessionManager.canShowLocker())
}
}
Loading
Loading