feat(android): wrap the store passphrase in the Android Keystore

Typing the passphrase on every launch was the v1 posture. It stays the
fallback, but it is no longer required: on first unlock the passphrase can be
remembered (checkbox, on by default) and is stored as an AES-256-GCM blob
wrapped by a key that never leaves the Android Keystore.

- crypto/StoreSecret.kt: the OWSEAL1 envelope (magic + IV + ciphertext + GCM
  tag) and the wipe helpers. No android.* imports, so the code that runs on a
  device is the code the unit tests exercise, with a JVM AES key standing in
  for the Keystore key.
- crypto/KeystorePassphraseCipher.kt: AES-256-GCM key under alias
  `onionwire.store`, StrongBox requested first (API 28+) with a graceful
  fallback on ProviderException (StrongBoxUnavailableException is one), and an
  honest KeyInfo-backed report of where the key actually lives.
  setUserAuthenticationRequired(false) stays the default on purpose.
- crypto/StoredPassphraseStore.kt: ciphertext only, at
  filesDir/secrets/store-passphrase.bin, written tmp+rename. A failed decrypt
  reports Unavailable and does NOT delete the blob.
- WireViewModel: unlock(passphrase, remember), unlockStored(),
  forgetStoredPassphrase(); the secret CharArray is zeroed in `finally`; the
  Keystore probe runs off the main thread at ViewModel construction.
- UnlockScreen: one-tap when a stored blob exists, the typed passphrase is
  dropped from Compose state as soon as it is handed over and is never put in
  saved instance state; "Forget stored passphrase" deletes blob and key.
- androidTest: the device-only half (AndroidKeyStore, StrongBox, KeyInfo),
  which cannot run in the unit-test JVM.

Verified: ./gradlew :app:assembleDebug and :app:testDebugUnitTest green,
25 tests / 0 failures (11 new StoreSecretTest, 9 new StoredPassphraseStoreTest).
This commit is contained in:
Sirius DevOps 2026-09-12 13:01:25 -04:00
commit 2fd640e230
No known key found for this signature in database
13 changed files with 1245 additions and 43 deletions

View file

@ -0,0 +1,150 @@
package com.siriusdevops.onionwire.crypto
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import android.util.Log
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.After
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotEquals
import org.junit.Assert.assertTrue
import org.junit.Assert.fail
import org.junit.Test
import org.junit.runner.RunWith
import java.io.File
/**
* The device half of the Keystore story. The unit-test JVM has no
* `AndroidKeyStore` provider, so nothing here can run as a plain JUnit test.
*
* Run on a real device or an emulator:
*
* ./gradlew :app:connectedDebugAndroidTest
*
* and read the `OnionWireKeystore` tag in logcat for the actual
* `KeyInfo`/`isInsideSecureHardware`/`securityLevel` report — the point of
* [key_backing_is_reported_and_logged] is to print the truth, not to assert a
* hardware-backed key on hardware that does not have one.
*/
@RunWith(AndroidJUnit4::class)
class KeystorePassphraseCipherTest {
private val context: Context =
InstrumentationRegistry.getInstrumentation().targetContext
private val cipher = KeystorePassphraseCipher(context)
private val passphrase = "correct horse battery staple".toCharArray()
@After
fun tearDown() {
cipher.deleteKey()
}
@Test
fun seal_open_round_trips_through_the_android_keystore() {
val blob = cipher.seal(passphrase)
assertTrue(
"envelope is magic + IV + ciphertext + tag",
blob.size >= passphrase.size + StoreSecret.IV_BYTES + 16 + 9,
)
val out = cipher.open(blob)
try {
assertArrayEquals(passphrase, out)
} finally {
StoreSecret.wipe(out)
}
}
@Test
fun stored_blob_on_a_device_is_not_the_plaintext() {
val dir = File(context.filesDir, "secrets-test")
dir.mkdirs()
val store = StoredPassphraseStore(File(dir, "store-passphrase.bin"), cipher)
try {
store.save(passphrase)
val raw = File(store.path).readBytes()
val needle = String(passphrase).toByteArray(Charsets.UTF_8)
assertFalse(
"the passphrase must not appear in the file",
String(raw, Charsets.ISO_8859_1).contains(String(needle, Charsets.ISO_8859_1)),
)
val loaded = store.load() as StoredPassphraseStore.Load.Loaded
try {
assertArrayEquals(passphrase, loaded.passphrase)
} finally {
StoreSecret.wipe(loaded.passphrase)
}
} finally {
store.forget()
dir.deleteRecursively()
}
}
@Test
fun key_backing_is_reported_and_logged() {
cipher.seal(passphrase) // force key creation
val strongBoxAdvertised = Build.VERSION.SDK_INT >= Build.VERSION_CODES.P &&
context.packageManager.hasSystemFeature(PackageManager.FEATURE_STRONGBOX_KEYSTORE)
val backing = cipher.backing()
Log.i(
"OnionWireKeystore",
"alias=${KeystorePassphraseCipher.ALIAS} backing=$backing " +
"strongBoxAdvertised=$strongBoxAdvertised " +
"sdk=${Build.VERSION.SDK_INT} device=${Build.MANUFACTURER} ${Build.MODEL}",
)
if (strongBoxAdvertised) {
assertTrue(
"StrongBox is advertised but the key did not land in a secure element: $backing",
backing == KeyBacking.STRONGBOX || backing == KeyBacking.HARDWARE,
)
} else {
assertNotEquals("the API refused to report the backing at all", KeyBacking.UNKNOWN, backing)
}
}
@Test
fun open_does_not_require_user_authentication() {
// The card's contract: unlocking must not need a fingerprint. If the
// key had been created with setUserAuthenticationRequired(true), this
// open() would throw UserNotAuthenticatedException.
val out = cipher.open(cipher.seal(passphrase))
StoreSecret.wipe(out)
assertTrue(cipher.keyPresent())
}
@Test
fun deleted_key_reports_unavailable_instead_of_crashing() {
val blob = cipher.seal(passphrase)
cipher.deleteKey()
assertFalse(cipher.keyPresent())
try {
cipher.open(blob)
fail("expected SecretUnavailable after the key was deleted")
} catch (e: SecretUnavailable) {
assertTrue(e.message!!.contains("gone"))
}
}
@Test
fun a_regenerated_key_cannot_open_an_old_blob() {
val blob = cipher.seal(passphrase)
cipher.deleteKey() // a reset that leaves the app's data dir intact
cipher.seal(passphrase) // same alias, brand-new key
try {
cipher.open(blob)
fail("expected SecretUnavailable for a blob wrapped by the deleted key")
} catch (_: SecretUnavailable) {
}
}
}