feat(phase-1/m3.2): FieldKeyProvider seam — AesGcmFieldCipher + EncryptionVerifier shared

Milestone M3 task 2 (DESKTOP_PHASE_PLAN §5): the cipher the desktop
build needs. AesGcmFieldCipher never touched Android APIs — only its
key SOURCE (ObjectBoxKeyProvider) did. New fun interface
FieldKeyProvider { getOrCreateKey(): ByteArray } in org.incido.data.crypto
is the seam; the class moves into the shared sources compiled by BOTH
:core:data (Android) and :core:data-jvm (desktop).

EncryptionVerifier (pure coroutines over NoteCryptoService) moves with
it — M3's desktop container needs the same trial-decrypt badge logic,
and the plan names the CipherHolder/NoteCryptoService/EncryptionVerifier
wiring as the thing to preserve.

Android diff is mechanical: AppContainer + SettingsViewModel pass
objectBoxKeyProvider::getOrCreateKey (SAM conversion) instead of the
provider object; NoteListViewModel's FQN import follows the package.
Behavior unchanged — same class, same bytes on the wire.

Justification for widening the seam (rules of engagement §9): the
interface replaces the concrete-class constructor parameter exactly as
planned; no other API moved.

Verified: ./gradlew assembleDebug (green) + ./gradlew :desktopApp:run
--args="--data-dir /tmp/incido-desktop-smoke --self-test --exit-after 6"
(green — :core:data-jvm compiles the shared crypto). One unrelated
GTK/XWayland window-startup wedge observed on a background run (process
never reached first composition; not reproducible on re-run, not a data
regression) — recorded for honesty.
This commit is contained in:
Incido Developer committed 2026-10-06 06:31:18 +13:00
1 parent 8db835640e
commit 40e2b9ff52
6 files changed
+46 -16

No files matched your search

@@ -0,0 +1,76 @@
package org.incido.data.crypto
import java.security.SecureRandom
import javax.crypto.Cipher
import javax.crypto.spec.GCMParameterSpec
import javax.crypto.spec.SecretKeySpec
/**
* v0.3.5.0: AES-256-GCM implementation of [FieldCipher] backed by the
* 32-byte key served by a [FieldKeyProvider].
*
* This is what actually makes "Encrypt in place" work: note content
* and attachment blobs are stored as
*
* ```
* nonce (12 bytes) | ciphertext | GCM tag (16 bytes, appended by JCE)
* ```
*
* AES-256 is the correct long-term choice for data-at-rest even under a
* post-quantum threat model — NIST considers AES-256 (GCM) to retain
* ~128-bit security against Grover's algorithm. The quantum-sensitive
* primitives (public-key exchange / signatures) are not used here.
*
* The key bytes are cached for the process lifetime (they already live
* in memory whenever the provider serves them at startup — Keystore
* unwrap on Android, key-file read on desktop).
*
* Phase 1 (M3 task 2): moved from :composeApp into the shared data layer
* behind the [FieldKeyProvider] seam — the class itself never touched
* Android APIs, only the key source did. Compiled for BOTH platforms.
*/
class AesGcmFieldCipher(keyProvider: FieldKeyProvider) : FieldCipher {
private val keyBytes: ByteArray = keyProvider.getOrCreateKey()
private val secretKey = SecretKeySpec(keyBytes, "AES")
private val secureRandom = SecureRandom()
override fun encryptString(plaintext: String): ByteArray =
encryptBytes(plaintext.toByteArray(Charsets.UTF_8))
override fun decryptString(blob: ByteArray): String =
decryptBytes(blob).toString(Charsets.UTF_8)
override fun encryptBytes(plaintext: ByteArray): ByteArray {
val nonce = ByteArray(NONCE_BYTES).also(secureRandom::nextBytes)
val cipher = Cipher.getInstance(TRANSFORMATION)
cipher.init(
Cipher.ENCRYPT_MODE,
secretKey,
GCMParameterSpec(GCM_TAG_BITS, nonce),
)
val cipherText = cipher.doFinal(plaintext)
return nonce + cipherText
}
override fun decryptBytes(blob: ByteArray): ByteArray {
require(blob.size > NONCE_BYTES) { "Encrypted blob is truncated" }
val nonce = blob.copyOfRange(0, NONCE_BYTES)
val cipherText = blob.copyOfRange(NONCE_BYTES, blob.size)
val cipher = Cipher.getInstance(TRANSFORMATION)
cipher.init(
Cipher.DECRYPT_MODE,
secretKey,
GCMParameterSpec(GCM_TAG_BITS, nonce),
)
// Throws AEADBadTagException on corruption / wrong key — this
// is the integrity signal the startup verifier relies on.
return cipher.doFinal(cipherText)
}
companion object {
private const val NONCE_BYTES = 12
private const val GCM_TAG_BITS = 128
private const val TRANSFORMATION = "AES/GCM/NoPadding"
}
}
@@ -0,0 +1,83 @@
package org.incido.data.crypto
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
/**
* v0.3.5.0: runs the note-encryption integrity check and exposes the
* result as observable state for the UI.
*
* Contract (per product requirement): the "Encrypted" badge on the
* note cards may ONLY be shown for notes that are **double-checked** —
* i.e. their stored ciphertext actually decrypts cleanly under the
* current Keystore key (the AES-GCM auth tag is the integrity proof).
* The settings flag alone never earns the badge.
*
* The check runs:
* 1. On every app open ([checkNow] from Application.onCreate), and
* 2. After each encryption migration completes (enable or disable),
* so the badge set always reflects the current on-disk state.
*
* v0.3.5.1: replaced the `if (_checking.value) return` skip-guard with
* a [Mutex] so concurrent calls actually serialize instead of being
* silently dropped. The previous implementation could miss the
* post-migration re-check when the startup check was still in flight
* on a phone with many notes — the new call would early-out, the old
* (stale, pre-encryption) result would win the race, and the cards
* never earned the badge until the user toggled off+on or restarted.
* The mutex lets every call take its turn in invocation order; the
* startup check is cheap (no encrypted rows yet) so user-triggered
* checks after a real migration only wait milliseconds.
*/
class EncryptionVerifier(
private val cryptoService: NoteCryptoService,
private val scope: CoroutineScope,
) {
private val _verification = MutableStateFlow<EncryptionVerification?>(null)
/** Latest verification result. `null` until the first check completes. */
val verification: StateFlow<EncryptionVerification?> = _verification.asStateFlow()
private val _verifiedNoteIds = MutableStateFlow<Set<Long>>(emptySet())
/** Set of note ids whose ciphertext verified cleanly. Empty before
* the first check — the badge is hidden until then. */
val verifiedNoteIds: StateFlow<Set<Long>> = _verifiedNoteIds.asStateFlow()
/**
* Serializes [checkNow] calls so every caller gets a turn and the
* LAST call's result wins. Without this, concurrent checks could
* race the StateFlow and a stale pre-migration result could
* overwrite a fresh post-migration one.
*/
private val mutex = Mutex()
init {
// Mirror the verified-id set out of every verification result.
scope.launch(Dispatchers.Default) {
verification.collect { result ->
_verifiedNoteIds.value = result?.verifiedNoteIds ?: emptySet()
}
}
}
/**
* Kick off a full re-verification on the IO pool. Safe to call
* repeatedly — calls are serialized via [mutex] in invocation
* order; the most recent call always produces the final
* `_verification` value, so the StateFlow always reflects the
* latest store state.
*/
fun checkNow() {
scope.launch(Dispatchers.IO) {
mutex.withLock {
_verification.value = cryptoService.verifyAll()
}
}
}
}
@@ -0,0 +1,24 @@
package org.incido.data.crypto
/**
* Phase 1 (M3 task 2): the platform seam the field cipher is built on.
*
* [AesGcmFieldCipher] only ever needs "the 32-byte field key, get it or
* make one" — everything else about where the key lives is platform
* territory:
*
* - Android: `ObjectBoxKeyProvider` (Keystore-wrapped key persisted in
* DataStore) is passed as `objectBoxKeyProvider::getOrCreateKey`.
* - Desktop: a JVM key provider (M3 task 3) reads/generates a `0600`
* key file, or installs the key imported through an
* [org.incido.compose.data.backup.EncryptedKeyCodec] recovery
* envelope.
*
* Declared `fun interface` so both platforms can pass a plain function
* reference / lambda instead of a class.
*/
fun interface FieldKeyProvider {
/** Return the 32-byte field key, creating and persisting one if none
* exists yet. Idempotent; blocking by design (startup call site). */
fun getOrCreateKey(): ByteArray
}