everysync: any undecryptable relay record aborts the cycle instead of merging a subset
- Commit
002e3239c9ffc381247e90d0de9d14b8b7c30b85- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-01 15:53 UTC (4 days ago)
- Parents
c0b8303
pullRemoteOrAbort only aborted when EVERY record failed decryption; a partially-decryptable log (key rotated, this device still on the old key) folded the decrypted subset as if it were full remote state — against the documented fail-closed contract. In the proven sequence the local edit was appended under the old key and marked clean, the newer remote notes never appeared, and the edit was permanently lost once the device reached the new key. RelayBlobStore also advanced its since cursor past undecryptable blobs, skipping them forever. Any undecryptable record now aborts with zero appends, writes, baseline or cursor mutations; blob folds still apply decryptable blobs but the cursor holds until a clean pull. No envelope or key changes. Two regression tests pin both behaviours. Verified: :everysync:testDevUnitTest 194 tests pass; lint errors are pre-existing on untouched files.
Diff
everysync/src/main/java/com/vayunmathur/everysync/network/remote/RelaySync.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/network/remote/RelaySync.kt b/everysync/src/main/java/com/vayunmathur/everysync/network/remote/RelaySync.ktindex 5562d016fc..1fad21494d 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/network/remote/RelaySync.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/network/remote/RelaySync.kt@@ -420,8 +420,9 @@ object RelaySync { /** * One decrypted record-log pull. [rawCount] is the envelope count on the * relay; [undecryptable] is how many failed to decrypt under the vault key.- * When most records fail to decrypt the key/epoch is suspect — the caller- * must treat that as a failure (abort), not as an empty vault.+ * When ANY record fails to decrypt the key/epoch is suspect and the fold+ * is unprovable as full state — record-log callers must treat that as a+ * failure (abort), not as a vault holding only the decrypted subset. */ class RecordsResult( val items: List<String>,
everysync/src/main/java/com/vayunmathur/everysync/provider/E2eeProvider.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/provider/E2eeProvider.kt b/everysync/src/main/java/com/vayunmathur/everysync/provider/E2eeProvider.ktindex f783e58851..afdf858a6b 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/provider/E2eeProvider.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/provider/E2eeProvider.kt@@ -267,9 +267,14 @@ class E2eeProvider : SyncProvider { // would delete every baseline-present row (see RelayMerge). val pulled = RelaySync.pullRecords(channel, vaultKey, 0) ?: throw VaultSyncAbort(CH_PULL_TRANSPORT, channelType)- if (pulled.fullyUndecryptable) {- // Records exist but none decrypt under this epoch key: re-key or- // epoch fetch is needed, not a merge of an "empty" vault.+ if (pulled.undecryptable > 0) {+ // ANY undecryptable record makes this fold unprovable as full+ // state: the hidden envelopes may hold newer edits, new records+ // or tombstones for ids the decrypted subset still shows, and+ // merging the subset would let local rows win by default and be+ // re-appended under the wrong key (silently lost once this+ // device reaches the current epoch). Re-key / epoch fetch is+ // needed, not a merge of a partial vault. throw VaultSyncAbort(CH_UNDECRYPTABLE_LOG, channelType) } return pulled
everysync/src/main/java/com/vayunmathur/everysync/sync/RelayBlobStore.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/sync/RelayBlobStore.kt b/everysync/src/main/java/com/vayunmathur/everysync/sync/RelayBlobStore.ktindex 957894b65d..8834f6832b 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/sync/RelayBlobStore.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/sync/RelayBlobStore.kt@@ -113,7 +113,7 @@ object RelayBlobStore { val since = RelayCursorStore.get(context, "notes", vaultId, channel) val result = RelaySync.pullRecords(channel, vaultKey, since) ?: return emptyList() if (result.items.isEmpty()) {- if (result.fullyUndecryptable) {+ if (result.undecryptable > 0) { // Records exist but none decrypt: a key/epoch problem, not an // empty blob log. Do NOT advance the cursor; retry next cycle. Log.status(TAG, "pull $channel: ${result.rawCount} records, none decryptable; skipping")@@ -127,7 +127,20 @@ object RelayBlobStore { for (env in latest.values) { if (applyPulledBlob(context, vaultId, env)) changed += env }- RelayCursorStore.advance(context, "notes", vaultId, channel, result.seq)+ // Advance past this batch only when every envelope decrypted: the+ // cursor is a `since`, so advancing past an undecryptable envelope+ // would skip it forever even after the correct epoch key arrives.+ // Decryptable envelopes still apply above (blob folds are per-name,+ // so a partial apply cannot misread absence as deletion).+ if (result.undecryptable == 0) {+ RelayCursorStore.advance(context, "notes", vaultId, channel, result.seq)+ } else {+ Log.status(+ TAG,+ "pull $channel: ${result.undecryptable} of ${result.rawCount} envelopes " ++ "undecryptable; cursor held at $since",+ )+ } return changed }
everysync/src/test/java/com/vayunmathur/everysync/PartialDecryptAbortTest.kt
diff --git a/everysync/src/test/java/com/vayunmathur/everysync/PartialDecryptAbortTest.kt b/everysync/src/test/java/com/vayunmathur/everysync/PartialDecryptAbortTest.ktnew file mode 100644index 0000000000..c7dd714b8a--- /dev/null+++ b/everysync/src/test/java/com/vayunmathur/everysync/PartialDecryptAbortTest.kt@@ -0,0 +1,127 @@+package com.vayunmathur.everysync++import android.app.Application+import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.everysync.auth.AccountConfig+import com.vayunmathur.everysync.auth.TokenStore+import com.vayunmathur.everysync.data.RemoteNote+import com.vayunmathur.everysync.data.VaultMeta+import com.vayunmathur.everysync.data.VaultStore+import com.vayunmathur.everysync.data.sink.NoteSink+import com.vayunmathur.everysync.network.remote.RelayCursorStore+import com.vayunmathur.everysync.network.remote.RelaySync+import com.vayunmathur.everysync.provider.CH_UNDECRYPTABLE_LOG+import com.vayunmathur.everysync.provider.DataType+import com.vayunmathur.everysync.provider.E2eeProvider+import com.vayunmathur.everysync.provider.SyncDirection+import com.vayunmathur.everysync.provider.VaultSyncAbort+import com.vayunmathur.everysync.sync.NoteRelayStore+import com.vayunmathur.everysync.sync.RelayBlobStore+import com.vayunmathur.everysync.sync.adapters.NoteKind+import javax.crypto.spec.SecretKeySpec+import kotlin.io.encoding.Base64+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++/**+ * Regression: a relay log that only PARTIALLY decrypts under the current+ * vault key (e.g. this device still holds the pre-rotation key while newer+ * envelopes ride the new epoch) is not provable full state. Merging the+ * decrypted subset let local rows win by default and re-appended them under+ * the wrong key — edits silently lost once the device reached the current+ * epoch, and new records never appeared. The cycle must abort instead.+ */+@RunWith(RobolectricTestRunner::class)+@Config(application = Application::class)+class PartialDecryptAbortTest {+ private val ctx: Context get() = ApplicationProvider.getApplicationContext()+ private val relay get() = RelaySuccessTest.sharedRelay++ @BeforeTest fun setUp() {+ relay.install()+ FakeIpcProvider.install(NoteSink.AUTHORITY)+ val softwareKey = SecretKeySpec(ByteArray(32) { (it * 7 + 1).toByte() }, "AES")+ com.vayunmathur.everysync.data.VaultKeyStore.secretKeyForTest = softwareKey+ TokenStore.getInstance(ctx).secretKeyForTest = softwareKey+ }++ private suspend fun makeVault(vaultId: String): Pair<VaultMeta, ByteArray> {+ val key = RelaySync.newVaultKey()+ val meta = VaultMeta(+ vaultId = vaultId, dataType = "notes", title = "T-notes",+ keyB64 = Base64.encode(key), ownerDeviceId = RelaySync.deviceId,+ ownerKeyB64 = Base64.encode(RelaySync.publicBundle), isOwner = true,+ )+ VaultStore.upsert(ctx, meta)+ com.vayunmathur.everysync.provider.SyncState.set(ctx, ACCOUNT, "e2ee_vault_notes", vaultId)+ return VaultStore.get(ctx, vaultId)!! to key+ }++ private fun config() = AccountConfig(ACCOUNT, "e2ee", setOf(DataType.NOTES))++ @Test fun partialDecryptAbortsNotesMerge() { runBlocking {+ assertTrue(RelaySync.init(ctx))+ val (meta, key) = makeVault("v-partial1")+ val provider = E2eeProvider()+ val channel = RelaySync.recordChannel("notes", meta.vaultId)+ // Baseline: one note synced cleanly under the current key.+ NoteSink.upsert(ctx, meta.vaultId, RemoteNote(uid = "n1", title = "Original", updatedAt = 1_000))+ provider.sync(ctx, config(), SyncDirection.BOTH)+ assertEquals(1, relay.channel(channel).size)+ val baselineHash = NoteRelayStore(ctx, meta.vaultId).loadBaseline()["n1"]?.contentHash+ assertNotNull(baselineHash)+ // The vault rotates (or a peer writes under the new epoch): a newer+ // edit of n1 and a new note n2 land under a key this device lacks.+ val newKey = RelaySync.newVaultKey()+ RelaySync.appendRecords(+ channel, newKey,+ listOf(+ NoteKind.toJson(RemoteNote(uid = "n1", title = "Edited remotely", updatedAt = 2_000)),+ NoteKind.toJson(RemoteNote(uid = "n2", title = "Remote only", updatedAt = 2_000)),+ ),+ )+ assertEquals(3, relay.channel(channel).size)+ // A local edit made before the next cycle must not be pushed under+ // the stale key, applied over, or marked clean against a partial fold.+ NoteSink.upsert(ctx, meta.vaultId, RemoteNote(uid = "n1", title = "Local edit", updatedAt = 3_000))+ val thrown = runCatching { provider.sync(ctx, config(), SyncDirection.BOTH) }.exceptionOrNull()+ val abort = thrown as? VaultSyncAbort+ assertNotNull(abort, "$thrown")+ assertEquals(CH_UNDECRYPTABLE_LOG, abort.code)+ // Zero relay appends, zero local writes, zero baseline mutations.+ assertEquals(3, relay.channel(channel).size)+ val local = NoteSink.listLocal(ctx, meta.vaultId)+ assertEquals("Local edit", local.single { it.uid == "n1" }.title)+ assertTrue(local.none { it.uid == "n2" })+ assertEquals(baselineHash, NoteRelayStore(ctx, meta.vaultId).loadBaseline()["n1"]?.contentHash)+ } }++ @Test fun blobPullHoldsCursorOnPartialDecrypt() { runBlocking {+ assertTrue(RelaySync.init(ctx))+ val vaultId = "v-blob-partial"+ val key = RelaySync.newVaultKey()+ val channel = RelayBlobStore.blobChannel(vaultId)+ assertNotNull(RelayBlobStore.push(vaultId, key, listOf("a.png" to "imgbytes".encodeToByteArray()), updatedAt = 1_000))+ // One envelope under a key this device does not hold yet.+ RelaySync.appendRecords(channel, RelaySync.newVaultKey(), listOf(RelayBlobStore.encode("b.png", byteArrayOf(1, 2), 2_000)))+ // Decryptable blobs still apply, but the cursor must not advance past+ // the undecryptable envelope or it would be skipped forever.+ val first = RelayBlobStore.pull(ctx, vaultId, key)+ assertEquals(listOf("a.png"), first.map { it.name })+ assertNotNull(RelayBlobStore.readLocal(ctx, vaultId, "a.png"))+ assertEquals(0, RelayCursorStore.get(ctx, "notes", vaultId, channel))+ // Re-pulling the held batch is a no-op locally and still holds.+ assertTrue(RelayBlobStore.pull(ctx, vaultId, key).isEmpty())+ assertEquals(0, RelayCursorStore.get(ctx, "notes", vaultId, channel))+ } }++ private companion object { const val ACCOUNT = "alice" }+}