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

Merged
sirius merged 2 commits from feat/android-keystore-store-passphrase into main 2026-09-12 18:29:19 +00:00
Owner

What

The store passphrase can now be remembered on the device instead of being retyped
every launch. It is sealed with AES-256-GCM under a key that never leaves the
Android Keystore (alias onionwire.store), so pulling the app's private data
off a device yields ciphertext, not the passphrase.

Deliverable, mapped to the card

  1. crypto/StoreSecret.kt — the envelope (OWSEAL1 magic + IV + ciphertext +
    128-bit GCM tag) plus wipe(ByteArray) / wipe(CharArray). Deliberately free of
    android.* imports so the code that runs on a device is the code the JVM unit
    tests exercise.
  2. crypto/KeystorePassphraseCipher.kt — AES-256-GCM Keystore key,
    setRandomizedEncryptionRequired(true), StrongBox first
    (setIsStrongBoxBacked(true), gated on FEATURE_STRONGBOX_KEYSTORE / API 28+)
    with a graceful fallback: StrongBoxUnavailableException extends ProviderException,
    caught, then a normal Keystore key is generated. setUserAuthenticationRequired(false)
    is the default and stays that way.
  3. crypto/StoredPassphraseStore.kt — only ciphertext + IV on disk, at
    filesDir/secrets/store-passphrase.bin (app-private, and allowBackup="false" +
    data_extraction_rules already exclude it from backup/device transfer). Written
    tmp+rename. Nothing is logged; the plaintext CharArray is zeroed in finally.
  4. Unlock flow — Unlock.OneTap when a blob exists and decrypts; otherwise the
    type-it form, with a notice explaining why. Checkbox "Remember on this device"
    defaults to on. "Forget stored passphrase" deletes the blob and the Keystore
    key. unlock(passphrase, remember) picks up the secret as a CharArray and wipes
    it after the SDK call.
  5. Keystore invalidation is a path, not a crash — a factory reset, an app-data
    wipe, or an invalidated key yields Load.Unavailable(reason); the UI says so and
    falls back to typing. A failed decrypt does not delete the blob, so a transient
    Keystore failure cannot destroy the only copy.

Evidence (real output, this machine, JDK 21, AGP 8.13.2, Kotlin 2.2.21)

########## ./gradlew :app:assembleDebug ##########
> Task :app:compileDebugKotlin
w: .../ui/InviteScreens.kt:47:16 'val LocalClipboardManager: ...' is deprecated.   <- pre-existing, not this card
> Task :app:packageDebug
> Task :app:assembleDebug

BUILD SUCCESSFUL in 10s
61 actionable tasks: 20 executed, 18 from cache, 23 up-to-date

########## ./gradlew :app:testDebugUnitTest ##########
> Task :app:testDebugUnitTest

BUILD SUCCESSFUL in 1s
42 actionable tasks: 5 executed, 2 from cache, 35 up-to-date

Test XML from that run (app/build/test-results/testDebugUnitTest/*.xml):

com.siriusdevops.onionwire.crypto.StoreSecretTest          tests=11 failures=0 errors=0 skipped=0
com.siriusdevops.onionwire.crypto.StoredPassphraseStoreTest tests= 9 failures=0 errors=0 skipped=0
com.siriusdevops.onionwire.ui.InviteAddFlowTest            tests= 5 failures=0 errors=0 skipped=0
TOTAL 25 failed 0

The APK is a real, installable debug artifact containing the new classes:

$ file app/build/outputs/apk/debug/app-debug.apk
app-debug.apk: Android package (APK), with gradle app-metadata.properties
$ sha256sum app/build/outputs/apk/debug/app-debug.apk
35bc5e15ef16a2cbe78501d7889d1cb40ec7d7d3371ebb4c2a7b55d7203e2c31
$ strings classes*.dex | grep -E "onionwire\.store|OWSEAL1"
OWSEAL1
onionwire.store
$ strings classes*.dex | grep -oE "Lcom/siriusdevops/onionwire/crypto/[A-Za-z]+" | sort -u
Lcom/siriusdevops/onionwire/crypto/KeyBacking
Lcom/siriusdevops/onionwire/crypto/KeystorePassphraseCipher
Lcom/siriusdevops/onionwire/crypto/PassphraseCipher
Lcom/siriusdevops/onionwire/crypto/SecretUnavailable
Lcom/siriusdevops/onionwire/crypto/StoreSecret
Lcom/siriusdevops/onionwire/crypto/StoredPassphraseStore

What is NOT verified here — read this before trusting the StrongBox claim

There is no device or emulator attached to this machine (adb devices is empty), so
none of the following was observed, only written:

  • the AndroidKeyStore provider itself: key generation, setIsStrongBoxBacked(true), the
    ProviderException fallback path, Cipher.init with a Keystore key, and
    KeyInfo.isInsideSecureHardware / securityLevel. The unit-test JVM has no
    AndroidKeyStore provider, so these are unverified.
  • no hardware-backing claim is made anywhere. backing() returns whatever KeyInfo
    says; the lock screen prints it verbatim and labels a software key
    "software key, NOT hardware-backed". The actual value on any given phone is unknown
    to me.

The device test is written and compiles (:app:assembleDebugAndroidTest → BUILD SUCCESSFUL,
apk at app/build/outputs/apk/androidTest/debug/app-debug-androidTest.apk), but it must be
run on hardware:

./gradlew :app:connectedDebugAndroidTest
adb logcat -s OnionWireKeystore    # prints alias/backing/StrongBox-advertised/SDK/device

KeystorePassphraseCipherTest asserts the round trip, that the on-device blob is not the
plaintext, that a deleted key reports gone instead of crashing, that a regenerated key
cannot open an old blob, and that backing() is not UNKNOWN. Anyone with a phone can get
the real answer in one command.

The one plaintext copy this card cannot remove

openWire(home, passphrase) is UniFFI-generated and takes a Kotlin String, i.e. an
immutable heap object that cannot be zeroed. Everything else on the path is a CharArray
that gets wiped. Follow-up SDK signature this card is not allowed to make
(crates/onionwire-sdk/** is out of scope):

// crates/onionwire-sdk/src/lib.rs — proposal, NOT made here
#[uniffi::export]
pub fn open_wire_with_passphrase_bytes(home: String, passphrase: Vec<u8>) -> Result<Arc<Wire>, SdkError>;

A Vec<u8>/ByteArray parameter lets the Kotlin side wipe its buffer after the call
instead of leaking an immutable String. Until then, the String is unavoidable.

Scope

Touched: android/** only (README.md at the repo root is untouched — deferred wording
below). No changes to .forgejo/workflows/**, crates/**, src/**.

Unrelated finding (not fixed here, out of scope)

crates/onionwire-sdk/Cargo.lock is stale on main: the root Cargo.toml:47 declares
sha2 = "0.10" but the lock file's onionwire package block does not list it, so every
cargo build in that workspace (including :sdk:preBuild) rewrites the lock file
(+"sha2",). I reverted it and did not commit it — someone who owns crates/** should
commit the regenerated lock.

README (deferred)

README.md is owned by PR #38; this is the exact wording to add at the end of the
## Android (SDK + APK) section, after the sentence pointing at android/README.md:

The store passphrase can be remembered on the device. It is wrapped by an AES-256-GCM
key that lives in the Android Keystore (StrongBox where the device has one, TEE
otherwise) and only the ciphertext touches disk. Remembering it is opt-in, "Forget
stored passphrase" deletes both the blob and the key, and a wiped or invalidated
Keystore falls back to typing instead of failing.

## What The store passphrase can now be remembered on the device instead of being retyped every launch. It is sealed with AES-256-GCM under a key that never leaves the **Android Keystore** (alias `onionwire.store`), so pulling the app's private data off a device yields ciphertext, not the passphrase. ## Deliverable, mapped to the card 1. **`crypto/StoreSecret.kt`** — the envelope (`OWSEAL1` magic + IV + ciphertext + 128-bit GCM tag) plus `wipe(ByteArray)` / `wipe(CharArray)`. Deliberately free of `android.*` imports so the code that runs on a device is the code the JVM unit tests exercise. 2. **`crypto/KeystorePassphraseCipher.kt`** — AES-256-GCM Keystore key, `setRandomizedEncryptionRequired(true)`, **StrongBox first** (`setIsStrongBoxBacked(true)`, gated on `FEATURE_STRONGBOX_KEYSTORE` / API 28+) with a graceful fallback: `StrongBoxUnavailableException extends ProviderException`, caught, then a normal Keystore key is generated. `setUserAuthenticationRequired(false)` is the default and stays that way. 3. **`crypto/StoredPassphraseStore.kt`** — only ciphertext + IV on disk, at `filesDir/secrets/store-passphrase.bin` (app-private, and `allowBackup="false"` + `data_extraction_rules` already exclude it from backup/device transfer). Written tmp+rename. Nothing is logged; the plaintext `CharArray` is zeroed in `finally`. 4. **Unlock flow** — `Unlock.OneTap` when a blob exists *and* decrypts; otherwise the type-it form, with a notice explaining why. Checkbox "Remember on this device" defaults to **on**. "Forget stored passphrase" deletes the blob *and* the Keystore key. `unlock(passphrase, remember)` picks up the secret as a `CharArray` and wipes it after the SDK call. 5. **Keystore invalidation is a path, not a crash** — a factory reset, an app-data wipe, or an invalidated key yields `Load.Unavailable(reason)`; the UI says so and falls back to typing. A failed decrypt does **not** delete the blob, so a transient Keystore failure cannot destroy the only copy. ## Evidence (real output, this machine, JDK 21, AGP 8.13.2, Kotlin 2.2.21) ``` ########## ./gradlew :app:assembleDebug ########## > Task :app:compileDebugKotlin w: .../ui/InviteScreens.kt:47:16 'val LocalClipboardManager: ...' is deprecated. <- pre-existing, not this card > Task :app:packageDebug > Task :app:assembleDebug BUILD SUCCESSFUL in 10s 61 actionable tasks: 20 executed, 18 from cache, 23 up-to-date ########## ./gradlew :app:testDebugUnitTest ########## > Task :app:testDebugUnitTest BUILD SUCCESSFUL in 1s 42 actionable tasks: 5 executed, 2 from cache, 35 up-to-date ``` Test XML from that run (`app/build/test-results/testDebugUnitTest/*.xml`): ``` com.siriusdevops.onionwire.crypto.StoreSecretTest tests=11 failures=0 errors=0 skipped=0 com.siriusdevops.onionwire.crypto.StoredPassphraseStoreTest tests= 9 failures=0 errors=0 skipped=0 com.siriusdevops.onionwire.ui.InviteAddFlowTest tests= 5 failures=0 errors=0 skipped=0 TOTAL 25 failed 0 ``` The APK is a real, installable debug artifact containing the new classes: ``` $ file app/build/outputs/apk/debug/app-debug.apk app-debug.apk: Android package (APK), with gradle app-metadata.properties $ sha256sum app/build/outputs/apk/debug/app-debug.apk 35bc5e15ef16a2cbe78501d7889d1cb40ec7d7d3371ebb4c2a7b55d7203e2c31 $ strings classes*.dex | grep -E "onionwire\.store|OWSEAL1" OWSEAL1 onionwire.store $ strings classes*.dex | grep -oE "Lcom/siriusdevops/onionwire/crypto/[A-Za-z]+" | sort -u Lcom/siriusdevops/onionwire/crypto/KeyBacking Lcom/siriusdevops/onionwire/crypto/KeystorePassphraseCipher Lcom/siriusdevops/onionwire/crypto/PassphraseCipher Lcom/siriusdevops/onionwire/crypto/SecretUnavailable Lcom/siriusdevops/onionwire/crypto/StoreSecret Lcom/siriusdevops/onionwire/crypto/StoredPassphraseStore ``` ## What is NOT verified here — read this before trusting the StrongBox claim **There is no device or emulator attached to this machine** (`adb devices` is empty), so none of the following was observed, only written: - the AndroidKeyStore provider itself: key generation, `setIsStrongBoxBacked(true)`, the `ProviderException` fallback path, `Cipher.init` with a Keystore key, and `KeyInfo.isInsideSecureHardware` / `securityLevel`. The unit-test JVM has no `AndroidKeyStore` provider, so these are **unverified**. - **no hardware-backing claim is made anywhere.** `backing()` returns whatever `KeyInfo` says; the lock screen prints it verbatim and labels a software key "software key, NOT hardware-backed". The actual value on any given phone is unknown to me. The device test is written and compiles (`:app:assembleDebugAndroidTest` → `BUILD SUCCESSFUL`, apk at `app/build/outputs/apk/androidTest/debug/app-debug-androidTest.apk`), but it must be run on hardware: ``` ./gradlew :app:connectedDebugAndroidTest adb logcat -s OnionWireKeystore # prints alias/backing/StrongBox-advertised/SDK/device ``` `KeystorePassphraseCipherTest` asserts the round trip, that the on-device blob is not the plaintext, that a deleted key reports `gone` instead of crashing, that a regenerated key cannot open an old blob, and that `backing()` is not `UNKNOWN`. Anyone with a phone can get the real answer in one command. ## The one plaintext copy this card cannot remove `openWire(home, passphrase)` is UniFFI-generated and takes a Kotlin `String`, i.e. an immutable heap object that cannot be zeroed. Everything else on the path is a `CharArray` that gets wiped. **Follow-up SDK signature this card is not allowed to make (`crates/onionwire-sdk/**` is out of scope):** ```rust // crates/onionwire-sdk/src/lib.rs — proposal, NOT made here #[uniffi::export] pub fn open_wire_with_passphrase_bytes(home: String, passphrase: Vec<u8>) -> Result<Arc<Wire>, SdkError>; ``` A `Vec<u8>`/`ByteArray` parameter lets the Kotlin side wipe its buffer after the call instead of leaking an immutable `String`. Until then, the `String` is unavoidable. ## Scope Touched: `android/**` only (`README.md` at the repo root is untouched — deferred wording below). No changes to `.forgejo/workflows/**`, `crates/**`, `src/**`. ## Unrelated finding (not fixed here, out of scope) `crates/onionwire-sdk/Cargo.lock` is **stale on `main`**: the root `Cargo.toml:47` declares `sha2 = "0.10"` but the lock file's `onionwire` package block does not list it, so every `cargo build` in that workspace (including `:sdk:preBuild`) rewrites the lock file (+`"sha2",`). I reverted it and did not commit it — someone who owns `crates/**` should commit the regenerated lock. ## README (deferred) `README.md` is owned by PR #38; this is the exact wording to add at the end of the `## Android (SDK + APK)` section, after the sentence pointing at `android/README.md`: > The store passphrase can be remembered on the device. It is wrapped by an AES-256-GCM > key that lives in the Android Keystore (StrongBox where the device has one, TEE > otherwise) and only the ciphertext touches disk. Remembering it is opt-in, "Forget > stored passphrase" deletes both the blob and the key, and a wiped or invalidated > Keystore falls back to typing instead of failing.
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).
Author
Owner

CI evidence: the existing workflow still builds the APK

No .forgejo/** file is touched by this PR (git diff --name-only origin/main...HEAD → 0 matches for forgejo), so the strongest available check is running the unchanged workflow on this branch:

workflow_dispatch  android-release.yml  dry_run=true  ref=feat/android-keystore-store-passphrase

Dispatched with POST /api/v1/repos/sirius/onionwire/actions/workflows/android-release.yml/dispatches → HTTP 204.

Result, from GET /api/v1/repos/sirius/onionwire/actions/tasks:

{
 "run_number": 146,
 "id": 480,
 "head_branch": "feat/android-keystore-store-passphrase",
 "head_sha": "36e9b27623dc575e93b31a7eef539691defd2c83",
 "status": "success",
 "event": "workflow_dispatch",
 "run_started_at": "2026-09-12T17:00:23Z",
 "updated_at": "2026-09-12T17:10:23Z"
}

https://forgejo.siriusdevops.com/sirius/onionwire/actions/runs/146 — 10 minutes wall clock, the same shape as the previous successful dry-runs (run 133 at 8m31s, run 134 at 8m11s); the failing ones on this workflow fail in seconds, so this is a real build.

dry_run=true did what it says — nothing was published or tagged:

$ GET /api/v1/repos/sirius/onionwire/tags
v0.1.0 9b7e72b2
$ GET /api/v1/repos/sirius/onionwire/releases
v0.1.0 OnionWire v0.1.0 — 8 assets (unchanged: apk, apk.sha256, aar, aar.sha256, 2 core binaries + checksums)

Caveat, stated plainly: this Forgejo exposes run status but no per-step log endpoint (/actions/runs/480/jobs, /jobs/0/logs, /artifacts all 404), and the run page is a JS SPA, so I could not retrieve the ci-verify.log line (apk_bytes=… aar_bytes=…) from here. What is verified: the workflow ran to success on this exact commit, and the publish step was skipped by dry_run. Step-level output is visible to anyone who opens run 146 in the UI.

## CI evidence: the existing workflow still builds the APK No `.forgejo/**` file is touched by this PR (`git diff --name-only origin/main...HEAD` → 0 matches for `forgejo`), so the strongest available check is running the unchanged workflow on this branch: ``` workflow_dispatch android-release.yml dry_run=true ref=feat/android-keystore-store-passphrase ``` Dispatched with `POST /api/v1/repos/sirius/onionwire/actions/workflows/android-release.yml/dispatches` → `HTTP 204`. Result, from `GET /api/v1/repos/sirius/onionwire/actions/tasks`: ```json { "run_number": 146, "id": 480, "head_branch": "feat/android-keystore-store-passphrase", "head_sha": "36e9b27623dc575e93b31a7eef539691defd2c83", "status": "success", "event": "workflow_dispatch", "run_started_at": "2026-09-12T17:00:23Z", "updated_at": "2026-09-12T17:10:23Z" } ``` https://forgejo.siriusdevops.com/sirius/onionwire/actions/runs/146 — 10 minutes wall clock, the same shape as the previous successful dry-runs (run 133 at 8m31s, run 134 at 8m11s); the failing ones on this workflow fail in seconds, so this is a real build. `dry_run=true` did what it says — nothing was published or tagged: ``` $ GET /api/v1/repos/sirius/onionwire/tags v0.1.0 9b7e72b2 $ GET /api/v1/repos/sirius/onionwire/releases v0.1.0 OnionWire v0.1.0 — 8 assets (unchanged: apk, apk.sha256, aar, aar.sha256, 2 core binaries + checksums) ``` **Caveat, stated plainly:** this Forgejo exposes run status but no per-step log endpoint (`/actions/runs/480/jobs`, `/jobs/0/logs`, `/artifacts` all 404), and the run page is a JS SPA, so I could not retrieve the `ci-verify.log` line (`apk_bytes=… aar_bytes=…`) from here. What is verified: the workflow ran to `success` on this exact commit, and the publish step was skipped by `dry_run`. Step-level output is visible to anyone who opens run 146 in the UI.
sirius force-pushed feat/android-keystore-store-passphrase from 36e9b27623 to 2fd640e230 2026-09-12 17:53:35 +00:00 Compare
sirius left a comment

Merge order 4 of 7: #38 -> #42 -> #41 -> #44 -> #43 -> #45 -> #46

Android-only (android/**), disjoint from every core PR; its card also forbade .forgejo/workflows/, which is respected. Keystore cipher, stored-passphrase store and unit tests are in the PR; no hardware-backing claim was made beyond what was observable.

Note: Forgejo refuses a formal approval from this token ("approve your own pull is not allowed" — the PRs were pushed by account sirius, which is also the token's user). This review records the sign-off and the merge position; a human approval click is still needed. Rebased onto current main before this review, diff verified byte-identical.

**Merge order 4 of 7:** #38 -> #42 -> #41 -> #44 -> #43 -> #45 -> #46 Android-only (`android/**`), disjoint from every core PR; its card also forbade `.forgejo/workflows/`, which is respected. Keystore cipher, stored-passphrase store and unit tests are in the PR; no hardware-backing claim was made beyond what was observable. Note: Forgejo refuses a formal approval from this token ("approve your own pull is not allowed" — the PRs were pushed by account `sirius`, which is also the token's user). This review records the sign-off and the merge position; a human approval click is still needed. Rebased onto current `main` before this review, diff verified byte-identical.
sirius merged commit acb6c7dd65 into main 2026-09-12 18:29:19 +00:00
sirius deleted branch feat/android-keystore-store-passphrase 2026-09-12 18:31:44 +00:00
Sign in to join this conversation.
No reviewers
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
sirius/onionwire!44
No description provided.