Modern Apps git

← Modern-Apps.git

library/e2ee-p2p: persisted identity halves are used only as a proven pair

Commit
5593e54e390d04d04e9cf45865f4280fadb89eaf
Author
Vayun Mathur <[email protected]>
When
2026-12-01 10:01 UTC (5 days ago)
Parents
f509b01
PqcIdentity trusted presence alone: isComplete tested only
that all four stored entries exist, and per-entry
onlyIfAbsent preserved survivors of a partial or
interleaved first-time write. A store holding e.g. a 3-byte
KEM 'public key' reloaded forever as a complete identity
whose encryptTo always failed in the native KEM path —
unusable and unrecoverable; a lone valid public half from
generation A paired silently with generation B's fresh
private half, so ciphertexts decapsulated under the wrong
key (GCM tag failure) and signatures failed verify against
the mixed bundle.

A persisted set is now used only if complete and both pairs
prove out on-device (KEM encrypt->decrypt round-trip and DSA
sign->verify probe; probe material never leaves the device).
Incomplete or mismatched sets regenerate wholesale — no
surviving half is ever re-paired — with the empty-store
onlyIfAbsent-plus-re-read race semantics kept, callers
serialized, and a bounded retry before loadOrCreate errors
rather than returning a broken identity; already-broken
persisted identities heal on next load. Three regression
tests (garbage halves, lone public half, complete-but-
mismatched set) assert round-trips and byte-identical
reload. Framing, nonces and fingerprints were audited and
cleared. Verified: :library:e2ee-p2p unit+native suites
pass, cargo test 28 pass, lint passes.

Diff

library/e2ee-p2p/AGENTS.md
diff --git a/library/e2ee-p2p/AGENTS.md b/library/e2ee-p2p/AGENTS.mdindex aebcab76ca..5a64d5e3a2 100644--- a/library/e2ee-p2p/AGENTS.md+++ b/library/e2ee-p2p/AGENTS.md@@ -11,9 +11,9 @@  ## Overview **Purpose:** End-to-end encryption + peer-to-peer primitives — PQC identity keys, AES content keys, safety numbers, invite fingerprints. Powers everysync vaults, voxels multiplayer, backup crypto. Relay/server sees ciphertext only.-**How to use:** Identities via `PqcIdentity` (Rust `PqcNative`); content via `E2ee` + `E2eeKeyStore`; verify contacts with `SecurityCode`/`InviteFingerprint`.+**How to use:** Identities via `PqcIdentity` (Rust `PqcNative`); content via `E2ee` + `E2eeKeyStore`; verify contacts with `SecurityCode`/`InviteFingerprint`. `PqcIdentity.loadOrCreate` uses a persisted key set only when it is complete and each private half verifies against its public half; an incomplete or mismatched set is regenerated wholesale. **Entry points:** `E2ee.kt` → `PqcIdentity.kt` → `PqcNative.kt` (Rust bridge).-**Gotchas:** Crypto changes need adversarial review; identity/key loss is unrecoverable by design — recovery flows (BIP-39 in backup) live in consumers, not here.+**Gotchas:** Crypto changes need adversarial review; identity/key loss is unrecoverable by design — recovery flows (BIP-39 in backup) live in consumers, not here. Builds arm64 + armeabi-v7a by default; `-PemulatorAbi=x86_64` additionally builds x86_64 for emulator runs of consumers.  ## Key files - com/vayunmathur/e2ee/E2ee.kt
library/e2ee-p2p/src/main/java/com/vayunmathur/e2ee/PqcIdentity.kt
diff --git a/library/e2ee-p2p/src/main/java/com/vayunmathur/e2ee/PqcIdentity.kt b/library/e2ee-p2p/src/main/java/com/vayunmathur/e2ee/PqcIdentity.ktindex ac45dddde5..589ad7a251 100644--- a/library/e2ee-p2p/src/main/java/com/vayunmathur/e2ee/PqcIdentity.kt+++ b/library/e2ee-p2p/src/main/java/com/vayunmathur/e2ee/PqcIdentity.kt@@ -1,5 +1,8 @@ package com.vayunmathur.e2ee +import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock+ /**  * A device's post-quantum identity for the Office app: an ML-KEM keypair (encryption) plus an  * ML-DSA keypair (signatures), persisted via an [E2eeKeyStore]. Keys are stored/handled as DER@@ -17,34 +20,67 @@ class PqcIdentity internal constructor(     /** Signs data with this identity's ML-DSA key. */     fun sign(data: ByteArray): ByteArray = Pqc.signWith(dsaPrivate, data) +    /**+     * True only if each private half matches the public half in [publicBundle]. Persisted+     * halves are individual store entries, so a partial write (crash mid-store, a store that+     * kept only some entries) or interleaved concurrent stores can leave two halves from+     * different generations side by side; presence of all four entries alone does not prove+     * they belong together. The probes stay on-device: an encrypt/decrypt round-trip for the+     * KEM pair and a sign/verify round-trip for the DSA pair.+     */+    private fun pairsConsistent(): Boolean = runCatching {+        val kemProbe = KEM_PROBE.encodeToByteArray()+        val encrypted = Pqc.encryptTo(publicBundle, kemProbe)+        if (!decrypt(encrypted).contentEquals(kemProbe)) return@runCatching false+        val dsaProbe = DSA_PROBE.encodeToByteArray()+        Pqc.verify(publicBundle, dsaProbe, sign(dsaProbe))+    }.getOrDefault(false)+     /** Loading and generation entry points for [PqcIdentity]. */     companion object {+        private const val KEM_PROBE = "pqc-identity-kem-pair-check-v1"+        private const val DSA_PROBE = "pqc-identity-dsa-pair-check-v1"+        private const val MAX_LOAD_ATTEMPTS = 3++        private val loadMutex = Mutex()+         /**          * Loads the persisted PQC keypairs, generating + storing them on first use.-         * Fixed race: re-read final persisted values after `onlyIfAbsent` stores-         * to avoid returning an ephemeral identity that would fail to decrypt.+         *+         * A persisted set is used only when it is complete and both pairs verify against+         * each other (see [pairsConsistent]). An incomplete or mismatched set is replaced+         * wholesale: keeping any surviving half and pairing it with a freshly generated+         * other half would publish a bundle whose private half belongs to a different+         * keypair, so nothing encrypted to it could ever be decrypted. First creation on an+         * empty store writes with `onlyIfAbsent` and re-reads the persisted winner; in-process+         * callers are serialised by [loadMutex], and a re-read that still fails the pair+         * check is overwritten on the next attempt rather than returned.          */-        suspend fun loadOrCreate(store: E2eeKeyStore, prefix: String = "pqc"): PqcIdentity {-            readPersisted(store, prefix)?.let { return it }-            generateAndStore(store, prefix)-            // Re-read final persisted (winner of concurrent race).-            return readPersisted(store, prefix) ?: error("PQC identity store returned no keys")-        }+        suspend fun loadOrCreate(store: E2eeKeyStore, prefix: String = "pqc"): PqcIdentity =+            loadMutex.withLock {+                var result: PqcIdentity? = null+                var attempt = 0+                while (result == null && attempt < MAX_LOAD_ATTEMPTS) {+                    attempt+++                    val keys = readKeys(store, prefix)+                    val persisted = keys.toIdentityOrNull()+                    if (persisted != null && persisted.pairsConsistent()) {+                        result = persisted+                    } else {+                        generateAndStore(store, prefix, overwrite = keys.hasAny)+                        val stored = readKeys(store, prefix).toIdentityOrNull()+                        if (stored != null && stored.pairsConsistent()) result = stored+                    }+                }+                result ?: error("PQC identity store returned no consistent keys")+            } -        private suspend fun readPersisted(store: E2eeKeyStore, prefix: String): PqcIdentity? {-            val keys = PqcKeys(-                kemPub = store.getBytes("${prefix}KemPub"),-                kemPriv = store.getBytes("${prefix}KemPriv"),-                dsaPub = store.getBytes("${prefix}DsaPub"),-                dsaPriv = store.getBytes("${prefix}DsaPriv")-            )-            if (!keys.isComplete) return null-            return PqcIdentity(-                Pqc.bundle(keys.kemPub!!, keys.dsaPub!!),-                keys.kemPriv!!,-                keys.dsaPriv!!-            )-        }+        private suspend fun readKeys(store: E2eeKeyStore, prefix: String): PqcKeys = PqcKeys(+            kemPub = store.getBytes("${prefix}KemPub"),+            kemPriv = store.getBytes("${prefix}KemPriv"),+            dsaPub = store.getBytes("${prefix}DsaPub"),+            dsaPriv = store.getBytes("${prefix}DsaPriv")+        )          private data class PqcKeys(             val kemPub: ByteArray?,@@ -52,20 +88,30 @@ class PqcIdentity internal constructor(             val dsaPub: ByteArray?,             val dsaPriv: ByteArray?         ) {-            val isComplete: Boolean-                get() = kemPub != null && kemPriv != null && hasDsaPair+            val hasAny: Boolean+                get() = kemPub != null || kemPriv != null || dsaPub != null || dsaPriv != null++            private val isComplete: Boolean+                get() = kemPub != null && kemPriv != null && dsaPub != null && dsaPriv != null -            private val hasDsaPair: Boolean-                get() = dsaPub != null && dsaPriv != null+            fun toIdentityOrNull(): PqcIdentity? {+                if (!isComplete) return null+                return PqcIdentity(+                    Pqc.bundle(kemPub!!, dsaPub!!),+                    kemPriv!!,+                    dsaPriv!!+                )+            }         } -        private suspend fun generateAndStore(store: E2eeKeyStore, prefix: String) {+        private suspend fun generateAndStore(store: E2eeKeyStore, prefix: String, overwrite: Boolean) {             val (kemPubNew, kemPrivNew) = Pqc.generateKem()             val (dsaPubNew, dsaPrivNew) = Pqc.generateDsa()-            store.setBytes("${prefix}KemPub", kemPubNew, onlyIfAbsent = true)-            store.setBytes("${prefix}KemPriv", kemPrivNew, onlyIfAbsent = true)-            store.setBytes("${prefix}DsaPub", dsaPubNew, onlyIfAbsent = true)-            store.setBytes("${prefix}DsaPriv", dsaPrivNew, onlyIfAbsent = true)+            val onlyIfAbsent = !overwrite+            store.setBytes("${prefix}KemPub", kemPubNew, onlyIfAbsent = onlyIfAbsent)+            store.setBytes("${prefix}KemPriv", kemPrivNew, onlyIfAbsent = onlyIfAbsent)+            store.setBytes("${prefix}DsaPub", dsaPubNew, onlyIfAbsent = onlyIfAbsent)+            store.setBytes("${prefix}DsaPriv", dsaPrivNew, onlyIfAbsent = onlyIfAbsent)         }     } }
library/e2ee-p2p/src/test/java/com/vayunmathur/e2ee/E2eeHkdfIdentityTest.kt
diff --git a/library/e2ee-p2p/src/test/java/com/vayunmathur/e2ee/E2eeHkdfIdentityTest.kt b/library/e2ee-p2p/src/test/java/com/vayunmathur/e2ee/E2eeHkdfIdentityTest.ktindex d1a94fdd3f..de7702b7da 100644--- a/library/e2ee-p2p/src/test/java/com/vayunmathur/e2ee/E2eeHkdfIdentityTest.kt+++ b/library/e2ee-p2p/src/test/java/com/vayunmathur/e2ee/E2eeHkdfIdentityTest.kt@@ -137,4 +137,69 @@ class E2eeHkdfIdentityTest {         assertTrue(store.map.containsKey("pqcDsaPub"))         assertTrue(identity.publicBundle.isNotEmpty())     }++    private fun assertIdentityUsable(identity: PqcIdentity) {+        val payload = "pair-check payload".encodeToByteArray()+        val ciphertext = Pqc.encryptTo(identity.publicBundle, payload)+        assertContentEquals(payload, identity.decrypt(ciphertext))+        val signed = "pair-check signed".encodeToByteArray()+        assertTrue(Pqc.verify(identity.publicBundle, signed, identity.sign(signed)))+    }++    @Test+    fun identityIncompleteStoreHealsToUsableIdentity() = runBlocking {+        val nativeAvailable = runCatching { Pqc.generateKem() }.isSuccess+        assertTrue(nativeAvailable, "host e2ee_pqc lib unavailable: cargoBuildHost must produce it for JVM tests")+        val store = MemStore()+        // Regression: previously the stale 3-byte halves won the onlyIfAbsent stores, so+        // the re-read identity was complete on paper but its KEM half could not even be+        // encapsulated to, and that state then persisted for every later load.+        store.map["pqcKemPub"] = byteArrayOf(1, 2, 3)+        store.map["pqcKemPriv"] = byteArrayOf(4, 5, 6)+        val identity = PqcIdentity.loadOrCreate(store)+        assertIdentityUsable(identity)+        // The healed identity is the one persisted: a reload yields it byte for byte.+        val reloaded = PqcIdentity.loadOrCreate(store)+        assertContentEquals(identity.publicBundle, reloaded.publicBundle)+        assertIdentityUsable(reloaded)+    }++    @Test+    fun identityLoneValidKemPubIsNotPairedWithFreshPrivate() = runBlocking {+        val nativeAvailable = runCatching { Pqc.generateKem() }.isSuccess+        assertTrue(nativeAvailable, "host e2ee_pqc lib unavailable: cargoBuildHost must produce it for JVM tests")+        val store = MemStore()+        // Regression: a crash after the first store kept this valid KEM public half; the+        // old code paired it with a different generation's private half, so ciphertexts+        // to the advertised bundle failed AES-GCM on decrypt.+        val (kemPub, _) = Pqc.generateKem()+        store.map["pqcKemPub"] = kemPub+        val identity = PqcIdentity.loadOrCreate(store)+        assertIdentityUsable(identity)+        val reloaded = PqcIdentity.loadOrCreate(store)+        assertContentEquals(identity.publicBundle, reloaded.publicBundle)+    }++    @Test+    fun identityMismatchedCompletePairsAreReplaced() = runBlocking {+        val nativeAvailable = runCatching { Pqc.generateKem() }.isSuccess+        assertTrue(nativeAvailable, "host e2ee_pqc lib unavailable: cargoBuildHost must produce it for JVM tests")+        val store = MemStore()+        // Regression: two interleaved first-time stores (or a torn write) can leave a+        // complete set whose public and private halves come from different generations.+        // Presence of all four entries must not be taken as a usable identity.+        val (kemPubA, _) = Pqc.generateKem()+        val (_, kemPrivB) = Pqc.generateKem()+        val (dsaPubA, _) = Pqc.generateDsa()+        val (_, dsaPrivB) = Pqc.generateDsa()+        store.map["pqcKemPub"] = kemPubA+        store.map["pqcKemPriv"] = kemPrivB+        store.map["pqcDsaPub"] = dsaPubA+        store.map["pqcDsaPriv"] = dsaPrivB+        val identity = PqcIdentity.loadOrCreate(store)+        assertIdentityUsable(identity)+        val reloaded = PqcIdentity.loadOrCreate(store)+        assertContentEquals(identity.publicBundle, reloaded.publicBundle)+        assertIdentityUsable(reloaded)+    } }