Modern Apps git

← Modern-Apps.git

findfamily: keep relay messages received before first unlock (#preunlock)

Commit
95a59d550b65c43c661b00f2508cbdb97147a51e
Author
Vayun Mathur <[email protected]>
When
2026-11-14 01:11 UTC (22 days ago)
Parents
2463a3c
Bug: after a reboot, before the first unlock, the pre-unlock tracking
path opens the live relay socket so the phone can keep publishing its
own location. The socket subscribes as us, and the relay immediately
hands it everything peers queued while the phone was off. A plain
subscription is not acknowledged, so once a frame is sent the server's
copy is gone. The pre-unlock path passed empty handlers
(`onLocations = {}, onUwb = {}`) because Room lives in credential-
encrypted storage and cannot be opened before unlock, so every drained
location and UWB envelope (including powered-off recovery grants) was
silently dropped. The code comment claimed peers' locations would be
"picked up on reconnect after unlock", but the relay had already
discarded them.

Fix: spool, don't drop.
- New `data/InboundSpool`: an append-only, length-prefixed file in
  device-protected storage (readable before unlock). Each MSG frame is
  stored exactly as the relay delivered it, still encrypted, and
  fsynced per frame. Nothing is decrypted or written in plaintext
  before unlock; the private key that opens these frames is already in
  device-protected storage (DirectBootStore), so holding the ciphertext
  there exposes nothing new.
- `Networking.startLive` / `superviseConnection` / `dispatchLiveFrame`
  take an optional `onRawMsg`; when set, MSG frames are handed over raw
  instead of decrypted and delivered. Only the pre-unlock socket sets
  it; the unlocked path is unchanged.
- On the unlocked path, `replayPreUnlockInbound()` runs right before the
  live socket starts: it feeds every spooled frame, oldest first,
  through the normal `dispatchLiveFrame` -> decrypt -> pair-ID check ->
  `processIncomingFixes` / `handleUwbEnvelopes` pipeline, then deletes
  the spool. Spooled (older) frames are therefore processed ahead of
  anything the new socket delivers. `promoteToUnlocked` already stops
  the pre-unlock socket before this runs.
- Replay progress is checkpointed after every frame (fsynced byte
  offset in a sidecar), so a process death mid-replay resumes where it
  stopped: no frame lost, at most the one in flight processed twice.
  A replay error stops at that frame and keeps the rest for the next
  start. A torn final record from a crash mid-append is ignored; every
  complete record before it is kept.
- Soft limit 64 MiB (~45k frames): past it the pre-unlock socket is
  closed so the relay keeps the rest queued for the unlocked socket,
  rather than growing the file without bound. Every frame already
  handed over is still written; pre-unlock publishing pauses in that
  (unrealistic) case instead of losing inbound data.

No protocol or server change; old servers and peers are unaffected.

Verified: new Robolectric InboundSpoolTest (order + cleanup, torn
record, failed replay resumes without loss or repeats, raw mode hands
MSG frames over undecrypted); :findfamily unit tests and lint via
gbuild.

Diff

findfamily/src/main/java/com/vayunmathur/findfamily/data/InboundSpool.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/data/InboundSpool.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/data/InboundSpool.ktnew file mode 100644index 0000000000..517a77fc1f--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/data/InboundSpool.kt@@ -0,0 +1,155 @@+package com.vayunmathur.findfamily.data++import android.content.Context+import java.io.DataInputStream+import java.io.DataOutputStream+import java.io.EOFException+import java.io.File+import java.io.FileOutputStream+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock+import kotlinx.coroutines.withContext++/**+ * Relay frames received before the first unlock, held until they can be processed.+ *+ * The relay hands queued messages to whichever socket subscribes as us, and a plain+ * subscription does not acknowledge them: once a frame is sent, the server's copy is gone.+ * Before the first unlock the Room database (credential-encrypted storage) cannot be opened,+ * so the pre-unlock socket cannot store a peer's location. It used to drop every frame it+ * drained, losing whatever peers had queued while this phone was off.+ *+ * This spool keeps those frames, still encrypted exactly as the relay delivered them, in a+ * length-prefixed file in device-protected storage, which is readable before unlock. The+ * unlocked path replays them through the normal inbound pipeline (decrypt, pair-ID check,+ * store) and then deletes the file. Nothing is decrypted or written in plaintext before+ * unlock. The private key that can open these frames is already in device-protected storage+ * (see [DirectBootStore]), so holding the ciphertext here exposes nothing new.+ *+ * Record format: `[u32 BE length][frame bytes]`, appended and fsynced per frame so a crash or+ * power loss keeps every frame already written. A torn final record (length written, bytes+ * short) is ignored on replay; every complete record before it is kept.+ */+object InboundSpool {+    private const val FILE_NAME = "ff_inbound_spool.bin"++    /**+     * Above this the pre-unlock path stops draining the relay (it closes its socket), so the+     * rest stays queued on the server for the unlocked socket instead of being written here.+     * 64 MiB is ~45k location frames: far more than a phone receives between a reboot and its+     * passcode in practice.+     */+    const val SOFT_LIMIT_BYTES: Long = 64L * 1024 * 1024++    private const val LENGTH_PREFIX_BYTES = 4++    /** Largest single frame accepted on replay; guards against reading a corrupt length. */+    private const val MAX_FRAME_BYTES = 16 * 1024 * 1024++    private val lock = Mutex()++    private fun file(context: Context): File =+        File(context.createDeviceProtectedStorageContext().filesDir, FILE_NAME)++    /**+     * Appends one frame. Returns the spool size afterwards, so the caller can stop draining+     * once it passes [SOFT_LIMIT_BYTES]. The frame is always written (never refused), so no+     * frame the server already handed over is lost to the limit.+     */+    suspend fun append(context: Context, frame: ByteArray): Long = lock.withLock {+        withContext(Dispatchers.IO) {+            val f = file(context)+            f.parentFile?.mkdirs()+            FileOutputStream(f, true).use { fos ->+                val out = DataOutputStream(fos)+                out.writeInt(frame.size)+                out.write(frame)+                out.flush()+                fos.fd.sync()+            }+            f.length()+        }+    }++    /**+     * Hands every spooled frame, oldest first, to [process], then deletes the spool.+     *+     * Progress is checkpointed after each frame (the byte offset of the next record, fsynced+     * to a small sidecar file), so if the process dies mid-replay the next drain resumes where+     * it stopped: no frame is lost, and at most the one frame in flight is processed twice.+     * If [process] throws, the drain stops at that frame and leaves it and everything after it+     * spooled for the next attempt.+     *+     * Returns the number of frames processed by this call.+     */+    suspend fun drain(context: Context, process: suspend (ByteArray) -> Unit): Int = lock.withLock {+        val f = file(context)+        val progress = progressFile(context)+        if (!withContext(Dispatchers.IO) { f.exists() }) {+            withContext(Dispatchers.IO) { progress.delete() }+            return@withLock 0+        }+        var offset = withContext(Dispatchers.IO) { readOffset(progress) }+        val records = withContext(Dispatchers.IO) { readFrom(f, offset) }+        var processed = 0+        for ((frame, next) in records) {+            process(frame)+            offset = next+            withContext(Dispatchers.IO) { writeOffset(progress, offset) }+            processed+++        }+        withContext(Dispatchers.IO) {+            f.delete()+            progress.delete()+        }+        processed+    }++    private fun progressFile(context: Context): File =+        File(context.createDeviceProtectedStorageContext().filesDir, "$FILE_NAME.done")++    private fun readOffset(progress: File): Long =+        runCatching { progress.readText().trim().toLong() }.getOrDefault(0L).coerceAtLeast(0L)++    private fun writeOffset(progress: File, offset: Long) {+        FileOutputStream(progress, false).use { fos ->+            fos.write(offset.toString().toByteArray())+            fos.flush()+            fos.fd.sync()+        }+    }++    /** Complete records starting at byte [start], each with the offset of the record after it. */+    private fun readFrom(f: File, start: Long): List<Pair<ByteArray, Long>> {+        val out = ArrayList<Pair<ByteArray, Long>>()+        DataInputStream(f.inputStream().buffered()).use { input ->+            var pos = 0L+            while (pos < start) {+                val skipped = input.skip(start - pos)+                if (skipped <= 0) return out+                pos += skipped+            }+            while (true) {+                val len = try {+                    input.readInt()+                } catch (_: EOFException) {+                    break+                }+                if (len < 0 || len > MAX_FRAME_BYTES) break+                val buf = ByteArray(len)+                try {+                    input.readFully(buf)+                } catch (_: EOFException) {+                    break // torn final record from a crash mid-append+                }+                pos += LENGTH_PREFIX_BYTES + len+                out.add(buf to pos)+            }+        }+        return out+    }++    /** Bytes taken by the length prefix of each record (for tests). */+    internal const val RECORD_OVERHEAD: Int = LENGTH_PREFIX_BYTES+}
findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingDirectBoot.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingDirectBoot.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingDirectBoot.ktindex 263279f261..ead72a5da4 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingDirectBoot.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingDirectBoot.kt@@ -11,6 +11,7 @@ import com.vayunmathur.library.log.Log import com.vayunmathur.findfamily.R import com.vayunmathur.findfamily.data.Coord import com.vayunmathur.findfamily.data.DirectBootStore+import com.vayunmathur.findfamily.data.InboundSpool import com.vayunmathur.findfamily.data.LocationValue import com.vayunmathur.findfamily.platform.keepAliveTick import com.vayunmathur.findfamily.platform.refreshFixCeiling@@ -60,9 +61,17 @@ internal fun LocationTrackingService.startDirectBootTracking() {             registerSensors()             startMovingNow()         }-        // Inbound delivery needs Room to persist anything, so the pre-unlock socket is-        // publish-only. Peers' locations are picked up on reconnect after unlock.-        Networking.startLive(serviceScope, onLocations = {}, onUwb = {})+        // Room (credential-encrypted) can't be opened before unlock, so inbound pushes can't be+        // stored yet. The relay forgets a frame once it has sent it to a plain subscriber, so+        // the frames are spooled, still encrypted, to device-protected storage and replayed+        // through the normal pipeline after unlock (see InboundSpool). Before this, every+        // frame drained here was silently dropped.+        Networking.startLive(+            serviceScope,+            onLocations = {},+            onUwb = {},+            onRawMsg = { frame -> spoolPreUnlockFrame(frame) },+        )          val sharing = DirectBootStore.isGlobalSharingEnabled(ctx)         val targets = if (sharing) DirectBootStore.roster(ctx) else emptyList()@@ -81,6 +90,55 @@ internal fun LocationTrackingService.startDirectBootTracking() {     } } +/**+ * Keeps one inbound relay frame received before unlock. Past [InboundSpool.SOFT_LIMIT_BYTES]+ * the pre-unlock socket is closed so the relay keeps the rest queued for the unlocked socket;+ * publishing pauses until unlock in that (unrealistic) case rather than losing inbound data.+ */+// Broad catch is deliberate: a spool write failure must be logged, never kill the socket reader.+@Suppress("TooGenericExceptionCaught")+internal suspend fun LocationTrackingService.spoolPreUnlockFrame(frame: ByteArray) {+    try {+        val size = InboundSpool.append(this, frame)+        if (size > InboundSpool.SOFT_LIMIT_BYTES) {+            Log.status(+                LocationTrackingService.TAG_DIRECT_BOOT,+                "pre-unlock spool at $size bytes; closing the socket so the relay keeps the rest"+            )+            Networking.stopLive()+        }+    } catch (e: CancellationException) {+        throw e+    } catch (e: Exception) {+        Log.status(LocationTrackingService.TAG_DIRECT_BOOT, "pre-unlock spool write failed", e)+    }+}++/**+ * Replays relay frames spooled before unlock through the normal inbound pipeline (decrypt,+ * pair-ID authentication, storage, UWB handling), oldest first, then clears the spool.+ * Called on the unlocked path before the live socket starts, so spooled (older) frames are+ * processed ahead of anything the new socket delivers.+ */+// Broad catch is deliberate: a replay failure leaves the spool for the next start, never blocks tracking.+@Suppress("TooGenericExceptionCaught")+internal suspend fun LocationTrackingService.replayPreUnlockInbound() {+    try {+        val n = InboundSpool.drain(this) { frame ->+            dispatchLiveFrame(+                frame,+                onLocations = { processIncomingFixes(it) },+                onUwb = { handleUwbEnvelopes(it) },+            )+        }+        if (n > 0) Log.status(LocationTrackingService.TAG_DIRECT_BOOT, "replayed $n pre-unlock frame(s)")+    } catch (e: CancellationException) {+        throw e+    } catch (e: Exception) {+        Log.status(LocationTrackingService.TAG_DIRECT_BOOT, "pre-unlock replay failed; kept for next start", e)+    }+}+ /** The pre-unlock equivalent of [syncHeartbeat]: publish only, no database, no enrichment. */ // Broad catch is deliberate: one peer's publish failure must not abort the pre-unlock publish loop. @Suppress("TooGenericExceptionCaught")
findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingService.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingService.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingService.ktindex 174af76aef..0a2ac95c7d 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingService.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingService.kt@@ -460,6 +460,9 @@ class LocationTrackingService : Service(), SensorEventListener {             // heartbeat used to. This is the only inbound path — there is no HTTP poll.             // Inbound fixes arrive with their claimed pair ID attached (see InboundFix);             // processIncomingFixes authenticates, pins, and time-clamps before storing.+            // Frames received before the first unlock were spooled (still encrypted) by the+            // pre-unlock socket; process them first so they land ahead of newer pushes.+            replayPreUnlockInbound()             Networking.startLive(                 serviceScope,                 onLocations = { processIncomingFixes(it) },
findfamily/src/main/java/com/vayunmathur/findfamily/util/Networking.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/util/Networking.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/util/Networking.ktindex 2e44faac78..8d8f028d47 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/util/Networking.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/util/Networking.kt@@ -315,8 +315,9 @@ object Networking {     /**      * Start (or no-op if already running) the live relay loop. On connect it subscribes      * and registers this device's PQC bundle in one frame; [onLocations]/[onUwb] then-     * receive already-decrypted pushes. Reconnects with 1s→15s backoff — there is no-     * HTTP fallback, so a dropped socket is simply re-established.+     * receive already-decrypted pushes. With [onRawMsg] set, location/UWB pushes are handed+     * over still encrypted instead (the pre-unlock spool). Reconnects with 1s→15s backoff —+     * there is no HTTP fallback, so a dropped socket is simply re-established.      */     // @Synchronized (with stopLive) makes the check-and-set atomic. onStartCommand can     // fire concurrently (START_STICKY redelivery, ServiceRestartWorker, BootReceiver),@@ -329,6 +330,7 @@ object Networking {         scope: CoroutineScope,         onLocations: suspend (List<InboundFix>) -> Unit,         onUwb: suspend (List<UwbEnvelope>) -> Unit,+        onRawMsg: (suspend (ByteArray) -> Unit)? = null,     ) {         if (liveJob?.isActive == true) return         stopLive()@@ -347,7 +349,7 @@ object Networking {                         wsSession = this                         sendSubscribe()                         backoff = BACKOFF_INITIAL_MS-                        superviseConnection(connScope, outerScope, onLocations, onUwb)+                        superviseConnection(connScope, outerScope, onLocations, onUwb, onRawMsg)                     }                 }.onFailure { Log.status(TAG, "live WS loop error", it) }                 connScope.cancel()
findfamily/src/main/java/com/vayunmathur/findfamily/util/NetworkingLive.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/util/NetworkingLive.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/util/NetworkingLive.ktindex f1c7f13539..946cc34d3f 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/util/NetworkingLive.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/util/NetworkingLive.kt@@ -47,6 +47,7 @@ internal suspend fun WsSession.superviseConnection(     outerScope: CoroutineScope,     onLocations: suspend (List<InboundFix>) -> Unit,     onUwb: suspend (List<UwbEnvelope>) -> Unit,+    onRawMsg: (suspend (ByteArray) -> Unit)? = null, ) {     val lastInboundMs = AtomicLong(System.currentTimeMillis())     // Reader: decrypts and delivers inbound frames, refreshing liveness on@@ -59,7 +60,7 @@ internal suspend fun WsSession.superviseConnection(                 lastInboundMs.set(System.currentTimeMillis())                 when (frame) {                     is WebSocketClient.WsFrame.Binary ->-                        dispatchLiveFrame(frame.bytes, onLocations, onUwb)+                        dispatchLiveFrame(frame.bytes, onLocations, onUwb, onRawMsg)                     else -> Unit                 }             }@@ -89,15 +90,23 @@ internal suspend fun WsSession.superviseConnection(     } } -/** Parse one server frame and dispatch: MSG → decrypt+deliver; KEYRESP → complete the lookup. */+/**+ * Parse one server frame and dispatch: MSG → decrypt+deliver; KEYRESP → complete the lookup.+ *+ * With [onRawMsg] set, MSG frames are handed over still encrypted instead of being decrypted+ * and delivered. The pre-unlock socket uses this to spool them (see+ * [com.vayunmathur.findfamily.data.InboundSpool]) because it has nowhere to store a location;+ * the unlocked path later replays each spooled frame through this function without it.+ */ internal suspend fun dispatchLiveFrame(     buf: ByteArray,     onLocations: suspend (List<InboundFix>) -> Unit,     onUwb: suspend (List<UwbEnvelope>) -> Unit,+    onRawMsg: (suspend (ByteArray) -> Unit)? = null, ) {     val op = buf.firstOrNull() ?: return     when (op) {-        Networking.WS_OP_MSG -> handleLiveMsg(buf, onLocations, onUwb)+        Networking.WS_OP_MSG -> if (onRawMsg != null) onRawMsg(buf) else handleLiveMsg(buf, onLocations, onUwb)         Networking.WS_OP_GETKEY_RESP -> handleKeyResp(buf)         WS_OP_RESOLVE_RESP -> handleResolveResp(buf)         WS_OP_REPORT_GET_RESP -> handleReportGetResp(buf)
findfamily/src/test/java/com/vayunmathur/findfamily/data/InboundSpoolTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/data/InboundSpoolTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/data/InboundSpoolTest.ktnew file mode 100644index 0000000000..ae57ea1f87--- /dev/null+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/data/InboundSpoolTest.kt@@ -0,0 +1,94 @@+package com.vayunmathur.findfamily.data++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.findfamily.util.dispatchLiveFrame+import java.io.File+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * Pre-unlock inbound spool: frames the relay drains to the pre-unlock socket must survive+ * until the unlocked path replays them (they used to be dropped).+ */+@RunWith(AndroidJUnit4::class)+class InboundSpoolTest {+    private val context: Context = ApplicationProvider.getApplicationContext()+    private val dir: File get() = context.createDeviceProtectedStorageContext().filesDir+    private val spool: File get() = File(dir, "ff_inbound_spool.bin")++    @BeforeTest+    fun clean() {+        dir.listFiles()?.filter { it.name.startsWith("ff_inbound_spool") }?.forEach { it.delete() }+    }++    @AfterTest+    fun tearDown() = clean()++    private fun frame(i: Int) = byteArrayOf(0x03, 0x00) + "frame-$i".encodeToByteArray()++    @Test+    fun framesComeBackInOrderAndTheSpoolIsCleared() = runBlocking {+        val sizes = (1..3).map { InboundSpool.append(context, frame(it)) }+        assertEquals(sizes.sorted(), sizes, "size grows with each append")+        val seen = mutableListOf<ByteArray>()+        val n = InboundSpool.drain(context) { seen.add(it) }+        assertEquals(3, n)+        (1..3).forEach { assertContentEquals(frame(it), seen[it - 1]) }+        assertFalse(spool.exists(), "spool deleted after a full replay")+        assertEquals(0, InboundSpool.drain(context) { error("nothing left") })+    }++    @Test+    fun aTornFinalRecordIsIgnoredAndEarlierFramesKept() = runBlocking {+        InboundSpool.append(context, frame(1))+        InboundSpool.append(context, frame(2))+        // Simulate power loss mid-append: a length prefix promising 100 bytes, then 3 bytes.+        spool.appendBytes(byteArrayOf(0, 0, 0, 100, 1, 2, 3))+        val seen = mutableListOf<ByteArray>()+        InboundSpool.drain(context) { seen.add(it) }+        assertEquals(2, seen.size)+        assertContentEquals(frame(2), seen[1])+    }++    @Test+    fun aFailedReplayResumesWithoutLosingOrRepeatingFrames() = runBlocking {+        (1..4).forEach { InboundSpool.append(context, frame(it)) }+        val first = mutableListOf<ByteArray>()+        assertFailsWith<IllegalStateException> {+            InboundSpool.drain(context) {+                if (first.size == 2) error("pipeline unavailable")+                first.add(it)+            }+        }+        assertTrue(spool.exists(), "spool kept after a failed replay")+        val second = mutableListOf<ByteArray>()+        InboundSpool.drain(context) { second.add(it) }+        assertEquals(listOf(1, 2), first.map { it.decodeToString().substringAfter("frame-").toInt() })+        assertEquals(listOf(3, 4), second.map { it.decodeToString().substringAfter("frame-").toInt() })+        assertFalse(spool.exists())+    }++    @Test+    fun rawModeHandsMsgFramesOverWithoutDecrypting() = runBlocking {+        val raw = mutableListOf<ByteArray>()+        val msg = frame(7) // op 0x03 = MSG; not valid ciphertext, so decrypting would fail+        dispatchLiveFrame(+            msg,+            onLocations = { error("must not decrypt/deliver in raw mode") },+            onUwb = { error("must not decrypt/deliver in raw mode") },+            onRawMsg = { raw.add(it) },+        )+        assertEquals(1, raw.size)+        assertContentEquals(msg, raw.single())+    }+}