package com.cottondb.android.platform import androidx.biometric.BiometricManager import androidx.biometric.BiometricPrompt import androidx.fragment.app.FragmentActivity import android.os.Build import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicReference import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.launch import kotlinx.coroutines.suspendCancellableCoroutine import kotlinx.coroutines.withContext /** * The only Android seam that turns a user-presence prompt into a vault private key. * * The caller receives the base64url scalar only long enough to pass it as `vault.unlock`'s * call parameter. Cancelling the caller cancels the system prompt; a cancelled or failed * prompt never calls [VaultKeyring.unlock] and never falls back to an unprotected read. */ class VaultUnlock(private val keyring: VaultKeyring) { suspend fun unlock(activity: FragmentActivity): String { val request = withContext(Dispatchers.IO) { keyring.prepareUnlock() } return withContext(Dispatchers.Main.immediate) { authenticate(activity, request) } } private suspend fun authenticate(activity: FragmentActivity, request: VaultUnlockRequest): String = suspendCancellableCoroutine { continuation -> val availability = BiometricManager.from(activity).canAuthenticate(allowedAuthenticators()) if (availability != BiometricManager.BIOMETRIC_SUCCESS) { continuation.resumeWith(Result.failure(VaultUnlockUnavailableException(availabilityMessage(availability)))) return@suspendCancellableCoroutine } val completion = AtomicReference(null) val terminal = AtomicBoolean(false) fun finish(result: Result) { // Prompt callbacks arrive on main while the IO completion and a caller's // cancellation may arrive elsewhere. This single admission owns resumption. if (terminal.compareAndSet(false, true)) continuation.resumeWith(result) } val prompt = BiometricPrompt(activity, activity.mainExecutor, object : BiometricPrompt.AuthenticationCallback() { override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) { if (terminal.get()) return val cipher = result.cryptoObject?.cipher if (cipher == null) { finish(Result.failure(VaultUnlockAuthenticationException("The vault prompt did not return its cipher."))) return } // BiometricPrompt returns the cipher that was authenticated. Do not accept a // different one, and do the KeyStore finish/file write away from the UI thread. if (cipher !== request.cipher) { finish(Result.failure(VaultUnlockAuthenticationException("The vault prompt returned the wrong cipher."))) return } // Keep the file/decrypt work a child of the caller's Job. Activity-backed // callers cancel it as they leave the screen; this is not a detached secret // read that can outlive the prompt's owner. val job = CoroutineScope(continuation.context + Dispatchers.IO) .launchUnlock(request, ::finish) completion.set(job) if (terminal.get()) job.cancel() } override fun onAuthenticationError(errorCode: Int, errString: CharSequence) { val failure = if (errorCode in CANCELLED_ERRORS) { VaultUnlockCancelledException() } else { VaultUnlockAuthenticationException(errString.toString()) } finish(Result.failure(failure)) } // A failed scan is not terminal. BiometricPrompt keeps the same protected // CryptoObject and lets the person try again or cancel explicitly. override fun onAuthenticationFailed() = Unit }) continuation.invokeOnCancellation { if (terminal.compareAndSet(false, true)) { completion.get()?.cancel() // A coroutine may be cancelled from IO or a lifecycle callback. The // Fragment-backed prompt is manipulated only on its activity's UI thread. activity.runOnUiThread { prompt.cancelAuthentication() } } } prompt.authenticate(promptInfo(), BiometricPrompt.CryptoObject(request.cipher)) } private fun CoroutineScope.launchUnlock( request: VaultUnlockRequest, finish: (Result) -> Unit, ): Job = launch { try { val privateKey = keyring.unlock(request) finish(Result.success(privateKey)) } catch (failure: Throwable) { finish(Result.failure(failure)) } } private companion object { fun allowedAuthenticators(): Int = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { BiometricManager.Authenticators.BIOMETRIC_STRONG or BiometricManager.Authenticators.DEVICE_CREDENTIAL } else { // Android 10 and lower cannot use a CryptoObject together // with device-credential fallback. Do not present a fallback // that cannot authorize this exact private-key operation. BiometricManager.Authenticators.BIOMETRIC_STRONG } fun promptInfo(): BiometricPrompt.PromptInfo { val builder = BiometricPrompt.PromptInfo.Builder() .setTitle("Unlock your passwords") .setAllowedAuthenticators(allowedAuthenticators()) if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) { builder.setNegativeButtonText("Cancel") } return builder.build() } val CANCELLED_ERRORS = setOf( BiometricPrompt.ERROR_CANCELED, BiometricPrompt.ERROR_NEGATIVE_BUTTON, BiometricPrompt.ERROR_USER_CANCELED, ) fun availabilityMessage(code: Int): String = when (code) { BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED -> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { "This phone needs a screen lock or a strong biometric set up to unlock passwords." } else { "Android 10 and earlier need a fingerprint or another biometric set up to unlock passwords; passcode fallback starts on Android 11." } BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE -> "This phone has no biometric hardware for unlocking passwords." BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE -> "This phone's biometric hardware is unavailable right now." else -> "This phone cannot ask to unlock passwords right now." } } } /** A person cancelled the biometric sheet; callers treat this as a decision, never a retry. */ class VaultUnlockCancelledException : IllegalStateException("Vault unlock was cancelled.") /** Biometric availability or an authenticated-prompt failure that must remain visible. */ class VaultUnlockUnavailableException(message: String) : IllegalStateException(message) class VaultUnlockAuthenticationException(message: String) : IllegalStateException(message)