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:
1 parent
8db835640e
commit
40e2b9ff52
6 files changed
+46
-16
No files matched your search
@@ -1,72 +0,0 @@
|
||||
package org.incido.compose.data.security
|
||||
|
||||
import java.security.SecureRandom
|
||||
import javax.crypto.Cipher
|
||||
import javax.crypto.spec.GCMParameterSpec
|
||||
import javax.crypto.spec.SecretKeySpec
|
||||
import org.incido.data.crypto.FieldCipher
|
||||
|
||||
/**
|
||||
* v0.3.5.0: AES-256-GCM implementation of [FieldCipher] backed by the
|
||||
* Keystore-wrapped 32-byte key owned by [ObjectBoxKeyProvider].
|
||||
*
|
||||
* 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 [ObjectBoxKeyProvider] unwraps them at startup).
|
||||
*/
|
||||
class AesGcmFieldCipher(keyProvider: ObjectBoxKeyProvider) : 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"
|
||||
}
|
||||
}
|
||||
@@ -1,85 +0,0 @@
|
||||
package org.incido.compose.data.security
|
||||
|
||||
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
|
||||
import org.incido.data.crypto.EncryptionVerification
|
||||
import org.incido.data.crypto.NoteCryptoService
|
||||
|
||||
/**
|
||||
* 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()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,14 +7,14 @@ import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import org.incido.data.AndroidImageOrientationNormalizer
|
||||
import org.incido.data.ObjectBoxStore
|
||||
import org.incido.data.crypto.AesGcmFieldCipher
|
||||
import org.incido.data.crypto.CipherHolder
|
||||
import org.incido.data.crypto.EncryptionVerifier
|
||||
import org.incido.data.crypto.NoteCryptoService
|
||||
import org.incido.data.repository.NoteRepositoryImpl
|
||||
import org.incido.domain.repository.NoteRepository
|
||||
import org.incido.compose.data.backup.BackupManager
|
||||
import org.incido.compose.data.backup.CarnetImporter
|
||||
import org.incido.compose.data.security.AesGcmFieldCipher
|
||||
import org.incido.compose.data.security.EncryptionVerifier
|
||||
import org.incido.compose.data.security.ObjectBoxKeyProvider
|
||||
import org.incido.compose.data.security.SecurityManager
|
||||
import org.incido.compose.data.settings.SettingsRepository
|
||||
@@ -77,7 +77,9 @@ class AppContainer(context: Context) {
|
||||
init {
|
||||
val s = settingsRepository.snapshot()
|
||||
if (s.isEncryptionActive && objectBoxKeyProvider.hasKeyBlocking()) {
|
||||
cipherHolder.cipher = AesGcmFieldCipher(objectBoxKeyProvider)
|
||||
// M3 task 2 seam: the cipher only needs the key bytes; the
|
||||
// Keystore-wrapped provider is passed as a plain function.
|
||||
cipherHolder.cipher = AesGcmFieldCipher(objectBoxKeyProvider::getOrCreateKey)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -53,7 +53,7 @@ data class NoteListUiState(
|
||||
class NoteListViewModel(
|
||||
private val repository: NoteRepository,
|
||||
/** v0.3.5.0 — source of the verified-encryption badge set. */
|
||||
private val encryptionVerifier: org.incido.compose.data.security.EncryptionVerifier? = null,
|
||||
private val encryptionVerifier: org.incido.data.crypto.EncryptionVerifier? = null,
|
||||
) : ViewModel() {
|
||||
|
||||
private val filterMode = MutableStateFlow<NoteFilter>(NoteFilter.Home)
|
||||
|
||||
@@ -15,11 +15,11 @@ import kotlinx.coroutines.launch
|
||||
import org.incido.compose.IncidoApplication
|
||||
import org.incido.compose.data.backup.BackupManager
|
||||
import org.incido.compose.data.backup.CarnetImporter
|
||||
import org.incido.compose.data.security.AesGcmFieldCipher
|
||||
import org.incido.compose.data.security.EncryptionVerifier
|
||||
import org.incido.compose.data.security.ObjectBoxKeyProvider
|
||||
import org.incido.compose.data.security.SecurityManager
|
||||
import org.incido.data.crypto.AesGcmFieldCipher
|
||||
import org.incido.data.crypto.CipherHolder
|
||||
import org.incido.data.crypto.EncryptionVerifier
|
||||
import org.incido.data.crypto.NoteCryptoService
|
||||
import org.incido.compose.data.settings.AutoLockTimeout
|
||||
import org.incido.compose.data.settings.SettingsRepository
|
||||
@@ -141,7 +141,8 @@ class SettingsViewModel(
|
||||
if (enabled) {
|
||||
// Key first (idempotent), cipher into the holder, sweep.
|
||||
objectBoxKeyProvider.getOrCreateKey()
|
||||
cipherHolder.cipher = AesGcmFieldCipher(objectBoxKeyProvider)
|
||||
cipherHolder.cipher =
|
||||
AesGcmFieldCipher(objectBoxKeyProvider::getOrCreateKey)
|
||||
noteCryptoService.encryptAllInPlace { done, total ->
|
||||
_migrationState.value = MigrationState.Running(
|
||||
if (total == 0) 1f else done.toFloat() / total,
|
||||
@@ -320,7 +321,8 @@ class SettingsViewModel(
|
||||
// Swap the live cipher to point at the freshly-installed key.
|
||||
// We build a new wrapper that re-reads the (just-persisted)
|
||||
// wrapped blob — no need to re-implement the unwrap here.
|
||||
cipherHolder.cipher = AesGcmFieldCipher(objectBoxKeyProvider)
|
||||
cipherHolder.cipher =
|
||||
AesGcmFieldCipher(objectBoxKeyProvider::getOrCreateKey)
|
||||
encryptionVerifier.checkNow()
|
||||
_snackbar.value = if (overwroteExisting) {
|
||||
"Recovery key installed. Previously-encrypted notes will appear as unverified."
|
||||
|
||||
Reference in new issue
Block a user