sync: purge old note tombstones; office documents stay deleted
- Commit
4099bc3461c528412f57e99ddf27a562aa87aea6- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-21 11:29 UTC (14 days ago)
- Parents
4ce730a
Notes tombstones accumulated forever. They are now purged at 90 days: everysync replays the full append-only relay log every cycle, so the relay - not the local row - is what keeps a deletion effective for returning peers, and 90 days covers thousands of 15-minute sync cycles. Purge runs in the existing startup IO slot and drops matching sync snapshots. Office had no delete tombstone at all, so a stale peer's op log could resurrect a deleted document. Owner-signed delete records on the deleted:<docId> channel are now honoured on every pull path: invites skipped, open blocked, sync no-ops, local CRDT state dropped. Op-log compaction was deliberately not done: there is no all-peers ack cursor, fresh peers rebuild from 0, and CRDT nodes anchor on deleted parents, so pruning could resurrect content. The reasoning is in the OfficeDocTombstones KDoc. Verified: notes 225 and office 1080 tests pass incl. stale- peer resurrection tests.
Diff
notes/src/main/java/com/vayunmathur/notes/MainActivity.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/MainActivity.kt b/notes/src/main/java/com/vayunmathur/notes/MainActivity.ktindex c0e2e38808..3918ea48f6 100644--- a/notes/src/main/java/com/vayunmathur/notes/MainActivity.kt+++ b/notes/src/main/java/com/vayunmathur/notes/MainActivity.kt@@ -46,6 +46,11 @@ class MainActivity : MaActivity() { notesRepository.migrateImageReferences(renames) NoteImageStore.pruneMigratedSources(applicationContext, renames) }+ // Opportunistic tombstone GC at app start (same IO/start-up slot+ // as the migrations above; notes has no sync worker of its own).+ // Tombstones are hidden from every list, so this never changes+ // what the first frame shows.+ notesRepository.purgeExpiredTombstones() withContext(Dispatchers.Main) { handleIntent(intent) ready = true
notes/src/main/java/com/vayunmathur/notes/data/NoteDatabase.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/data/NoteDatabase.kt b/notes/src/main/java/com/vayunmathur/notes/data/NoteDatabase.ktindex 32bf7dd091..f9379085a8 100644--- a/notes/src/main/java/com/vayunmathur/notes/data/NoteDatabase.kt+++ b/notes/src/main/java/com/vayunmathur/notes/data/NoteDatabase.kt@@ -73,6 +73,14 @@ abstract class NoteDao { @Query("DELETE FROM Note") abstract suspend fun deleteAll() + /**+ * Hard-removes tombstones older than [cutoffMillis] (see+ * [NotesRepository.purgeExpiredTombstones] for the horizon reasoning).+ * Live rows are never touched, however old they are.+ */+ @Query("DELETE FROM Note WHERE deleted = 1 AND updatedAt < :cutoffMillis")+ abstract suspend fun purgeTombstonesOlderThan(cutoffMillis: Long): Int+ /** Local batch write (list reorder, legacy import): bumps updatedAt like [upsert]. */ suspend fun upsertAll(values: List<Note>) { val now = nextStamp()@@ -96,6 +104,18 @@ interface NoteSyncSnapshotDao { @Query("DELETE FROM SyncSnapshot WHERE syncId = :syncId") suspend fun deleteBySyncId(syncId: String) + /**+ * Drops baseline snapshots for tombstones expired at [cutoffMillis], so+ * purging a tombstone does not leave its snapshot row behind. Must run+ * before the tombstone rows themselves are deleted (it finds them via+ * the Note table).+ */+ @Query(+ "DELETE FROM SyncSnapshot WHERE syncId IN " ++ "(SELECT syncId FROM Note WHERE deleted = 1 AND updatedAt < :cutoffMillis)",+ )+ suspend fun deleteForTombstonesOlderThan(cutoffMillis: Long): Int+ @Query("DELETE FROM SyncSnapshot") suspend fun deleteAll() }
notes/src/main/java/com/vayunmathur/notes/data/NotesRepository.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/data/NotesRepository.kt b/notes/src/main/java/com/vayunmathur/notes/data/NotesRepository.ktindex 174cf391fe..8855075eef 100644--- a/notes/src/main/java/com/vayunmathur/notes/data/NotesRepository.kt+++ b/notes/src/main/java/com/vayunmathur/notes/data/NotesRepository.kt@@ -63,6 +63,37 @@ class NotesRepository private constructor(context: Context) : /** Removes every note (including tombstones). Used when a relay vault is purged. */ suspend fun purge() = dao.deleteAll() + /**+ * Garbage-collects deleted-note tombstones older than+ * [TOMBSTONE_RETENTION_MS], plus their sync-baseline snapshots. Returns+ * how many tombstone rows were purged.+ *+ * Why 90 days is a safe horizon: the tombstone row is only the+ * *pre-push* proof of a delete. The sync driver (everysync's+ * `driveMerge`) pulls the FULL relay log from 0 on every cycle and+ * folds it latest-wins per syncId, so a fresh peer — and a peer+ * returning after a long offline stretch — re-fetches the+ * `deleted=true` envelope from the append-only relay no matter what+ * this table holds. Periodic sync runs at least every 15 minutes, so+ * 90 days leaves thousands of cycles for the deleting device to get+ * one successful push in; after that push the local row is redundant.+ * The accepted residual risk is a device that deletes while offline+ * and then gets no successful sync for over 90 days: its unpushed+ * tombstone can be purged here and the still-live relay copy pulled+ * back. [Note.updatedAt] is a hybrid stamp, so a row carrying a+ * future-skewed stamp is kept longer — the safe direction.+ *+ * Runs opportunistically at app start (see MainActivity), matching+ * this app's existing start-up migration scheduling; notes has no+ * sync worker of its own (sync lives in the everysync app, which+ * reaches this store through the relay ContentProvider).+ */+ suspend fun purgeExpiredTombstones(nowMs: Long = System.currentTimeMillis()): Int {+ val cutoff = tombstoneCutoff(nowMs)+ snapshotDao.deleteForTombstonesOlderThan(cutoff)+ return dao.purgeTombstonesOlderThan(cutoff)+ }+ suspend fun getAllSnapshots(): List<SyncSnapshot> = snapshotDao.getAll() suspend fun upsertSnapshot(snapshot: SyncSnapshot) = snapshotDao.upsert(snapshot) suspend fun deleteSnapshotBySyncId(syncId: String) = snapshotDao.deleteBySyncId(syncId)@@ -116,6 +147,12 @@ class NotesRepository private constructor(context: Context) : companion object { private const val LEGACY_DB_NAME = "passwords-db" + /** How long a deleted-note tombstone is kept before GC (see [purgeExpiredTombstones]). */+ const val TOMBSTONE_RETENTION_MS: Long = 90L * 24 * 60 * 60 * 1000++ /** Tombstones with a stamp strictly before this instant are expired at [nowMs]. */+ fun tombstoneCutoff(nowMs: Long): Long = nowMs - TOMBSTONE_RETENTION_MS+ @Volatile private var instance: NotesRepository? = null fun get(context: Context): NotesRepository = instance ?: synchronized(this) {
notes/src/test/java/com/vayunmathur/notes/data/NotesRepositoryTest.kt
diff --git a/notes/src/test/java/com/vayunmathur/notes/data/NotesRepositoryTest.kt b/notes/src/test/java/com/vayunmathur/notes/data/NotesRepositoryTest.ktindex 24e5d18085..ba31821b71 100644--- a/notes/src/test/java/com/vayunmathur/notes/data/NotesRepositoryTest.kt+++ b/notes/src/test/java/com/vayunmathur/notes/data/NotesRepositoryTest.kt@@ -63,6 +63,42 @@ class NotesRepositoryTest { assertNull(repo.getBySyncId("del-a")) } + @Test fun purgeExpiredTombstonesKeepsRecentAndLivePurgesOld() = runTest {+ val now = 1_800_000_000_000L+ val day = 24L * 60 * 60 * 1000+ // Live rows are never purged, however old.+ repo.upsertRaw(Note(title = "live-old", content = "", syncId = "gc-live", updatedAt = now - 200 * day))+ // Recent tombstone (inside the horizon) and one exactly at the+ // cutoff are kept: only strictly-older tombstones are purged.+ repo.upsertRaw(Note(title = "recent", content = "", syncId = "gc-recent", updatedAt = now - 10 * day, deleted = true))+ repo.upsertRaw(+ Note(+ title = "at-cutoff", content = "", syncId = "gc-cutoff",+ updatedAt = NotesRepository.tombstoneCutoff(now), deleted = true,+ ),+ )+ repo.upsertRaw(Note(title = "old", content = "", syncId = "gc-old", updatedAt = now - 91 * day, deleted = true))+ repo.upsertSnapshot(SyncSnapshot("gc-old", SyncSnapshot.KIND_NOTE, "h-old", 1, 2, 3))+ repo.upsertSnapshot(SyncSnapshot("gc-recent", SyncSnapshot.KIND_NOTE, "h-recent", 1, 2, 3))++ assertEquals(1, repo.purgeExpiredTombstones(now))++ assertEquals("live-old", repo.getBySyncId("gc-live")?.title)+ assertTrue(repo.getBySyncId("gc-recent")!!.deleted)+ assertTrue(repo.getBySyncId("gc-cutoff")!!.deleted)+ assertNull(repo.getBySyncId("gc-old"))+ // The expired tombstone's baseline snapshot goes with it; the+ // recent tombstone's snapshot is kept.+ assertEquals(listOf("gc-recent"), repo.getAllSnapshots().map { it.syncId })+ // A second run at the same instant is a no-op.+ assertEquals(0, repo.purgeExpiredTombstones(now))+ }++ @Test fun tombstoneRetentionIsNinetyDays() {+ assertEquals(90L * 24 * 60 * 60 * 1000, NotesRepository.TOMBSTONE_RETENTION_MS)+ assertEquals(1_000L - NotesRepository.TOMBSTONE_RETENTION_MS, NotesRepository.tombstoneCutoff(1_000L))+ }+ @Test fun updatedSinceUpsertAllAndSnapshots() = runTest { repo.upsertAllRaw(listOf( Note(title = "old", content = "", syncId = "u1", updatedAt = 10),
office/src/main/java/com/vayunmathur/office/platform/OfficeDocTombstones.kt
diff --git a/office/src/main/java/com/vayunmathur/office/platform/OfficeDocTombstones.kt b/office/src/main/java/com/vayunmathur/office/platform/OfficeDocTombstones.ktnew file mode 100644index 0000000000..005a96abe4--- /dev/null+++ b/office/src/main/java/com/vayunmathur/office/platform/OfficeDocTombstones.kt@@ -0,0 +1,262 @@+package com.vayunmathur.office.platform++import android.app.Application+import androidx.lifecycle.viewModelScope+import com.vayunmathur.library.util.DataStoreUtils+import com.vayunmathur.office.sync.OfficeSync+import com.vayunmathur.office.sync.sign+import com.vayunmathur.office.sync.verify+import kotlin.io.encoding.Base64+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch+import kotlinx.coroutines.sync.withLock+import kotlinx.coroutines.withContext+import kotlinx.serialization.Serializable++/**+ * A persisted record that an online document was deleted.+ *+ * Before this, deleting an online document had no representation at all:+ * the local index entry could go away, but the relay keeps the document's+ * whole op log forever, so the next pull by a stale peer (or a replayed+ * invite) rebuilt and re-listed a document everyone thought was gone.+ * A tombstone is the delete's durable proof, checked on every pull path:+ *+ * - [OfficeViewModel.pullInboxInvites] never re-adds a tombstoned doc+ * from an invite;+ * - [OfficeViewModel.openOnlineDocument] refuses a tombstoned doc and+ * honours a verified remote tombstone instead of pulling its ops;+ * - [OfficeViewModel.syncDoc] / live merges no-op for a tombstoned doc,+ * so ops pushed by a peer that has not seen the delete yet cannot+ * resurrect it;+ * - [OfficeViewModel.refreshOnline] sweeps the index for owner-signed+ * remote tombstones.+ *+ * An owner's delete is broadcast as an owner-signed [SignedDocDelete] on+ * the `deleted:<docId>` channel (the same pattern as `title:<docId>`),+ * and only owner-signed records are honoured from the relay: a member+ * deleting a document only removes it for themselves (local tombstone,+ * no broadcast), so no editor can delete a document for everyone.+ *+ * Tombstones are never garbage-collected here. Each one is a doc id plus+ * a timestamp — bounded by the number of documents a user deletes, not+ * by edits — and expiring one would re-open exactly the resurrection+ * window it exists to close, because the relay op log outlives it.+ *+ * There is deliberately no CRDT op-log compaction alongside this:+ * pruning relay ops below a cursor is unsafe in this design. The only+ * cursor is `crdtCursor:<docId>` (what THIS device has pulled) — the+ * roster carries no per-peer ack, so there is no all-peers-synced point+ * to prune below; the relay client offers append/pull only (no+ * truncate), and fresh peers rebuild by pulling from 0; and in the Rust+ * tree CRDT, deleted nodes are still `parent`/`left` anchors for later+ * nodes while `apply` re-inserts unknown ids, so a stale peer+ * re-delivering pre-prune ops would resurrect pruned nodes. The+ * `toStateNodesJson` re-baseline (see key rotation) appends a snapshot+ * on top of the old log rather than replacing it, so it is not a+ * compaction watermark either.+ */+@Serializable+data class OfficeDocTombstone(+ val docId: String,+ val deletedAt: Long,+ val author: String = "",+)++/** An owner-signed [OfficeDocTombstone] record, as carried on `deleted:<docId>`. */+@Serializable+data class SignedDocDelete(val tombstone: OfficeDocTombstone, val sig: String)++/** Pure encode/decode/filter helpers for the persisted tombstone list. */+object OfficeDocTombstones {+ /** DataStore key holding the JSON tombstone list. */+ const val KEY = "officeDeletedDocs"++ /** Canonical bytes the owner signs for a delete (binds doc + instant). */+ fun signingBytes(docId: String, deletedAt: Long): ByteArray =+ "$docId|deleted|$deletedAt".encodeToByteArray()++ fun encode(tombstones: List<OfficeDocTombstone>): String =+ OfficeSync.json.encodeToString(tombstones)++ /** Tolerant decode: a corrupt store reads as "no tombstones", never a crash. */+ fun decode(raw: String?): List<OfficeDocTombstone> =+ raw?.let {+ runCatching { OfficeSync.json.decodeFromString<List<OfficeDocTombstone>>(it) }.getOrNull()+ } ?: emptyList()++ fun isDeleted(tombstones: List<OfficeDocTombstone>, docId: String): Boolean =+ tombstones.any { it.docId == docId }++ /** Adds (or replaces, keeping the newest stamp) [tombstone] in [tombstones]. */+ fun upsert(+ tombstones: List<OfficeDocTombstone>,+ tombstone: OfficeDocTombstone,+ ): List<OfficeDocTombstone> {+ val existing = tombstones.firstOrNull { it.docId == tombstone.docId }+ if (existing != null && existing.deletedAt >= tombstone.deletedAt) return tombstones+ return tombstones.filterNot { it.docId == tombstone.docId } + tombstone+ }++ /** Index entries that survive [tombstones] (order preserved). */+ fun filterLive(+ metas: List<OfficeDocMeta>,+ tombstones: List<OfficeDocTombstone>,+ ): List<OfficeDocMeta> {+ if (tombstones.isEmpty()) return metas+ val deleted = tombstones.map { it.docId }.toSet()+ return metas.filterNot { it.docId in deleted }+ }+}++internal fun OfficeViewModel.loadTombstones(ds: DataStoreUtils): List<OfficeDocTombstone> =+ OfficeDocTombstones.decode(ds.getString(OfficeDocTombstones.KEY))++internal suspend fun OfficeViewModel.saveTombstones(+ ds: DataStoreUtils,+ tombstones: List<OfficeDocTombstone>,+) {+ ds.setString(OfficeDocTombstones.KEY, OfficeDocTombstones.encode(tombstones))+}++internal fun OfficeViewModel.isDocTombstoned(ds: DataStoreUtils, docId: String): Boolean =+ OfficeDocTombstones.isDeleted(loadTombstones(ds), docId)++/**+ * Records [tombstone] and removes every local trace of the document:+ * index entry, persisted CRDT tree, pull cursor, and un-acked pending+ * ops. After this, no pull path can list or rebuild the document.+ */+internal suspend fun OfficeViewModel.applyDocTombstone(+ ds: DataStoreUtils,+ tombstone: OfficeDocTombstone,+) {+ saveTombstones(ds, OfficeDocTombstones.upsert(loadTombstones(ds), tombstone))+ indexMutex.withLock {+ val index = loadIndex(ds)+ val live = OfficeDocTombstones.filterLive(index, listOf(tombstone))+ if (live.size != index.size) saveIndex(ds, live)+ }+ ds.removeKeys(+ listOf(+ "crdt:${tombstone.docId}",+ "crdtCursor:${tombstone.docId}",+ "crdtPending:${tombstone.docId}",+ ),+ )+ if (currentDocId == tombstone.docId) {+ OfficeSync.stopLive()+ currentTree?.close()+ currentTree = null+ currentDocId = null+ currentDocKey = null+ }+}++/**+ * Reads the `deleted:<docId>` channel and returns the newest tombstone+ * whose signature verifies against [ownerKey], or null. Like+ * [OfficeViewModel.fetchTitle], a failed pull means "unknown" (null),+ * never "not deleted".+ */+internal suspend fun OfficeViewModel.fetchDocDelete(+ docId: String,+ key: ByteArray,+ ownerKey: ByteArray?,+): OfficeDocTombstone? {+ if (ownerKey == null) return null+ val res = OfficeSync.pullDocActions("deleted:$docId", key, 0) ?: return null+ var latest: OfficeDocTombstone? = null+ for (item in res.items) {+ val signed = runCatching {+ syncJson.decodeFromString<SignedDocDelete>(item)+ }.getOrNull() ?: continue+ val verified = runCatching {+ OfficeSync.verify(+ ownerKey,+ OfficeDocTombstones.signingBytes(+ signed.tombstone.docId,+ signed.tombstone.deletedAt,+ ),+ Base64.decode(signed.sig),+ )+ }.getOrDefault(false)+ if (verified && signed.tombstone.docId == docId &&+ (latest == null || signed.tombstone.deletedAt > latest.deletedAt)+ ) {+ latest = signed.tombstone+ }+ }+ return latest+}++/** Checks the open document for a remote tombstone (rides the live poll, like [pollTitle]). */+internal suspend fun OfficeViewModel.pollDocDelete(docId: String, key: ByteArray) {+ if (currentDocId != docId) return+ val ds = DataStoreUtils.getInstance(getApplication())+ if (isDocTombstoned(ds, docId)) return+ val tombstone = fetchDocDelete(docId, key, currentOwnerKey) ?: return+ applyDocTombstone(ds, tombstone)+}++/** Sweeps every indexed document for a verified remote tombstone (called on refresh). */+internal suspend fun OfficeViewModel.sweepDeletedDocs(ds: DataStoreUtils) {+ val index = indexMutex.withLock { loadIndex(ds) }+ for (meta in index) {+ if (isDocTombstoned(ds, meta.docId)) continue+ val key = runCatching { Base64.decode(meta.keyB64) }.getOrNull() ?: continue+ val ownerKey = if (meta.owner) {+ runCatching { OfficeSync.publicBundle }.getOrNull()+ } else {+ meta.ownerKeyB64.takeIf { it.isNotBlank() }+ ?.let { runCatching { Base64.decode(it) }.getOrNull() }+ }+ val tombstone = runCatching { fetchDocDelete(meta.docId, key, ownerKey) }+ .getOrNull() ?: continue+ applyDocTombstone(ds, tombstone)+ }+}++/**+ * Deletes an online document for this device: persists a tombstone,+ * drops the local index/CRDT state, and — for the owner only —+ * broadcasts the owner-signed tombstone so peers honour it on their+ * next pull/open/refresh. A non-owner's delete is local-only.+ * [onResult] receives whether the local deletion was recorded.+ */+fun OfficeViewModel.deleteOnlineDocument(docId: String, onResult: (Boolean) -> Unit = {}) {+ viewModelScope.launch(Dispatchers.IO) {+ val ok = runCatching {+ OfficeSync.init(getApplication<Application>())+ val ds = DataStoreUtils.getInstance(getApplication())+ val meta = indexMutex.withLock { loadIndex(ds) }+ .firstOrNull { it.docId == docId }+ val tombstone = OfficeDocTombstone(+ docId = docId,+ deletedAt = System.currentTimeMillis(),+ author = OfficeSync.deviceId,+ )+ applyDocTombstone(ds, tombstone)+ // Owner only: sign + publish so peers can verify and honour it.+ // Fire-and-forget like the signed title channel: the local+ // tombstone is already durable if the relay is unreachable.+ if (meta != null && meta.owner) {+ val key = runCatching { Base64.decode(meta.keyB64) }.getOrNull()+ if (key != null) {+ val sig = Base64.encode(+ OfficeSync.sign(+ OfficeDocTombstones.signingBytes(docId, tombstone.deletedAt),+ ),+ )+ OfficeSync.appendDocActions(+ "deleted:$docId",+ key,+ listOf(syncJson.encodeToString(SignedDocDelete(tombstone, sig))),+ )+ }+ }+ true+ }.getOrDefault(false)+ withContext(Dispatchers.Main) { onResult(ok) }+ }+}
office/src/main/java/com/vayunmathur/office/platform/OfficeViewModelSyncA.kt
diff --git a/office/src/main/java/com/vayunmathur/office/platform/OfficeViewModelSyncA.kt b/office/src/main/java/com/vayunmathur/office/platform/OfficeViewModelSyncA.ktindex 8521cac50c..7740afb8d4 100644--- a/office/src/main/java/com/vayunmathur/office/platform/OfficeViewModelSyncA.kt+++ b/office/src/main/java/com/vayunmathur/office/platform/OfficeViewModelSyncA.kt@@ -130,6 +130,7 @@ internal fun OfficeViewModel.startLive(docId: String, key: ByteArray) { kotlinx.coroutines.delay(LIVE_POLL_MS) runCatching { syncDoc(docId, key) } runCatching { pollTitle(docId, key) } // pick up an owner rename ~live+ runCatching { pollDocDelete(docId, key) } // pick up an owner delete ~live } } // Presence upkeep: clear a peer's "typing…" a few seconds after they stop, and drop the whole@@ -174,6 +175,9 @@ internal fun OfficeViewModel.handleLive(raw: String, docId: String, key: ByteArr /** Merges locally-pending edits plus incoming live ops into the CRDT (caller holds [syncMutex]). */ internal suspend fun OfficeViewModel.applyLiveActions(msg: OfficeSync.LiveMsg, docId: String, key: ByteArray) {+ // A tombstoned doc ignores live ops: a peer that has not seen the+ // delete yet must not resurrect it through the live channel either.+ if (isDocTombstoned(DataStoreUtils.getInstance(getApplication()), docId)) return val tree = currentTree ?: return val startVersion = editVersion val localXml = exportFlat()
office/src/main/java/com/vayunmathur/office/platform/OfficeViewModelSyncB.kt
diff --git a/office/src/main/java/com/vayunmathur/office/platform/OfficeViewModelSyncB.kt b/office/src/main/java/com/vayunmathur/office/platform/OfficeViewModelSyncB.ktindex ae171c4fd2..0bd5ac1138 100644--- a/office/src/main/java/com/vayunmathur/office/platform/OfficeViewModelSyncB.kt+++ b/office/src/main/java/com/vayunmathur/office/platform/OfficeViewModelSyncB.kt@@ -151,6 +151,9 @@ fun OfficeViewModel.refreshOnline() { val ds = DataStoreUtils.getInstance(getApplication()) val res = pullInboxInvites(ds) ?: return@runCatching mergeRequests(ds, res)+ // Honour owner-signed delete tombstones for indexed docs before+ // anything below can re-list them.+ sweepDeletedDocs(ds) ds.setLong("officeInboxCursor", res.seq.toLong()) // Pick up any owner rename for docs we already have (network done outside the lock). refreshTitles(ds)@@ -165,8 +168,13 @@ internal suspend fun OfficeViewModel.pullInboxInvites(ds: DataStoreUtils): Offic if (res.invites.isEmpty()) return res indexMutex.withLock { val index = loadIndex(ds).associateBy { it.docId }.toMutableMap()+ // A tombstoned doc stays deleted: a replayed/stale invite must not+ // re-add it to the index.+ val deleted = loadTombstones(ds).map { it.docId }.toSet() for (inv in res.invites) {- if (!index.containsKey(inv.docId)) index[inv.docId] = officeDocMetaFromInvite(inv)+ if (inv.docId !in deleted && !index.containsKey(inv.docId)) {+ index[inv.docId] = officeDocMetaFromInvite(inv)+ } } saveIndex(ds, index.values.toList()) }@@ -249,6 +257,9 @@ internal fun OfficeViewModel.parseFlat(flat: String): OdfDocument? { */ internal suspend fun OfficeViewModel.syncDoc(docId: String, key: ByteArray) = syncMutex.withLock { val ds = DataStoreUtils.getInstance(getApplication())+ // Deleted docs stay deleted: never pull (or push) for a tombstoned doc,+ // so ops from a peer that has not seen the delete cannot resurrect it.+ if (isDocTombstoned(ds, docId)) return@withLock val tree = currentTree ?: (loadTree(ds, docId) ?: DocumentTreeCrdt(OfficeSync.deviceId)).also { currentTree = it } val cursor = ds.getLong("crdtCursor:$docId")?.toInt() ?: 0 val localXml = exportFlat()@@ -464,6 +475,21 @@ fun OfficeViewModel.openOnlineDocument(meta: OfficeDocMeta) { // Resolve the current content key (honors key rotations / read-revocation). val (epoch, key) = fetchCurrentKey(meta.docId, inviteKey, currentOwnerKey) currentEpoch = epoch+ // Deleted docs stay deleted: a locally tombstoned doc, or a+ // verified owner tombstone on the relay, blocks the open before+ // any doc ops are pulled — a stale peer's op log must not+ // rebuild a deleted document.+ val remoteTombstone = runCatching {+ fetchDocDelete(meta.docId, key, currentOwnerKey)+ }.getOrNull()+ if (remoteTombstone != null) applyDocTombstone(ds, remoteTombstone)+ if (remoteTombstone != null || isDocTombstoned(ds, meta.docId)) {+ withContext(Dispatchers.Main) {+ stateMutable.value =+ ViewState.Error("This document was deleted, so it can no longer be opened.")+ }+ return@runCatching+ } val crdt = loadTree(ds, meta.docId) ?: DocumentTreeCrdt(OfficeSync.deviceId) // Refresh the (owner-signed) roster so op role-checks are correct before applying. runCatching { fetchMembers(meta.docId, key, currentOwnerKey) }
office/src/main/java/com/vayunmathur/office/ui/OfficeOnlineScreens.kt
diff --git a/office/src/main/java/com/vayunmathur/office/ui/OfficeOnlineScreens.kt b/office/src/main/java/com/vayunmathur/office/ui/OfficeOnlineScreens.ktindex 2852aa9e83..441e0885e9 100644--- a/office/src/main/java/com/vayunmathur/office/ui/OfficeOnlineScreens.kt+++ b/office/src/main/java/com/vayunmathur/office/ui/OfficeOnlineScreens.kt@@ -43,6 +43,7 @@ import com.vayunmathur.library.ui.DropdownMenuItem import com.vayunmathur.library.ui.ExperimentalMaterial3Api import com.vayunmathur.library.ui.ExternalIntents import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconDelete import com.vayunmathur.library.ui.IconRefresh import com.vayunmathur.library.ui.IconShare import com.vayunmathur.library.ui.ListItem@@ -58,6 +59,7 @@ import com.vayunmathur.office.platform.OfficeMember import com.vayunmathur.office.platform.OfficeRoles import com.vayunmathur.office.platform.OfficeViewModel import com.vayunmathur.office.platform.approveJoinRequest+import com.vayunmathur.office.platform.deleteOnlineDocument import com.vayunmathur.office.platform.denyRequest import com.vayunmathur.office.platform.enableOnlineSharing import com.vayunmathur.office.platform.initSync@@ -241,6 +243,7 @@ private fun OnlineDocCard( context: android.content.Context, onOpenDoc: (OfficeDocMeta) -> Unit, ) {+ var confirmDelete by remember { mutableStateOf(false) } Card(Modifier.fillMaxWidth().clickable { onOpenDoc(meta) }) { ListItem( content = { Text(meta.title) },@@ -254,14 +257,43 @@ private fun OnlineDocCard( ) }, trailingContent = {- // Owners can share a tappable invite link (public ids only).- if (meta.owner) IconButton(onClick = {- ExternalIntents.shareText(- context,- viewModel.shareLinkFor(meta.docId),- context.getString(R.string.share_link_chooser))- }) { IconShare() }+ Row {+ // Owners can share a tappable invite link (public ids only).+ if (meta.owner) IconButton(onClick = {+ ExternalIntents.shareText(+ context,+ viewModel.shareLinkFor(meta.docId),+ context.getString(R.string.share_link_chooser))+ }) { IconShare() }+ IconButton(onClick = { confirmDelete = true }) { IconDelete() }+ } } ) }+ if (confirmDelete) {+ AlertDialog(+ onDismissRequest = { confirmDelete = false },+ title = { Text(stringResource(R.string.delete_document)) },+ text = {+ Text(+ stringResource(+ if (meta.owner) R.string.delete_document_message+ else R.string.remove_document_message,+ meta.title,+ ),+ )+ },+ confirmButton = {+ TextButton(onClick = {+ confirmDelete = false+ viewModel.deleteOnlineDocument(meta.docId)+ }) { Text(stringResource(R.string.delete_document)) }+ },+ dismissButton = {+ TextButton(onClick = { confirmDelete = false }) {+ Text(stringResource(UiR.string.cancel))+ }+ },+ )+ } }
office/src/main/res/values/strings.xml
diff --git a/office/src/main/res/values/strings.xml b/office/src/main/res/values/strings.xmlindex eb7c70009f..66f6c79990 100644--- a/office/src/main/res/values/strings.xml+++ b/office/src/main/res/values/strings.xml@@ -385,6 +385,12 @@ <string name="table">Table</string> <!-- OfficeBottomBar: Action delete row. Verb phrase. --> <string name="delete_row">Delete row</string>+ <!-- OnlineTab: Action delete online document. Verb phrase. -->+ <string name="delete_document">Delete document</string>+ <!-- OnlineTab: Delete confirmation body. %1$s=document title. -->+ <string name="delete_document_message">Delete “%1$s” for everyone it is shared with? This cannot be undone.</string>+ <!-- OnlineTab: Delete confirmation body for a document shared with you. %1$s=document title. -->+ <string name="remove_document_message">Remove “%1$s” from your documents? It will stay available to everyone else.</string> <!-- OfficeBottomBar: Number format General --> <string name="general">General</string> <!-- OfficeBottomBar: Number format Integer -->
office/src/test/java/com/vayunmathur/office/platform/OfficeDocTombstoneTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/platform/OfficeDocTombstoneTest.kt b/office/src/test/java/com/vayunmathur/office/platform/OfficeDocTombstoneTest.ktnew file mode 100644index 0000000000..490ebe2ea3--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/platform/OfficeDocTombstoneTest.kt@@ -0,0 +1,324 @@+package com.vayunmathur.office.platform++import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.e2ee.E2ee+import com.vayunmathur.e2ee.E2eeKeyStore+import com.vayunmathur.e2ee.PqcIdentity+import com.vayunmathur.library.network.SimpleResponse+import com.vayunmathur.library.ui.odf.OdfContentBlock+import com.vayunmathur.library.ui.odf.OdfDocument+import com.vayunmathur.library.ui.odf.OdfParagraph+import com.vayunmathur.library.ui.odf.OdfSpan+import com.vayunmathur.library.util.DataStoreUtils+import java.util.concurrent.CountDownLatch+import java.util.concurrent.TimeUnit+import kotlin.io.encoding.Base64+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.test.UnconfinedTestDispatcher+import kotlinx.coroutines.test.resetMain+import kotlinx.coroutines.test.runTest+import kotlinx.coroutines.test.setMain+import com.vayunmathur.office.domain.DocumentTreeCrdt+import com.vayunmathur.office.sync.OfficeSync+import com.vayunmathur.office.sync.seal+import com.vayunmathur.office.sync.sign++/**+ * Doc-delete tombstones: pure list helpers, plus ViewModel pull paths+ * against a fake relay. The resurrection scenario under test is a stale+ * peer/pull replaying what it still holds (an invite, or the deleted+ * doc's whole op log) after the delete — the tombstone must win.+ */[email protected](org.robolectric.RobolectricTestRunner::class)+@OptIn(ExperimentalCoroutinesApi::class)+class OfficeDocTombstoneTest {++ private class MemStore : E2eeKeyStore {+ private val m = HashMap<String, ByteArray>()+ override suspend fun getBytes(name: String): ByteArray? = m[name]+ override suspend fun setBytes(name: String, value: ByteArray, onlyIfAbsent: Boolean) {+ if (onlyIfAbsent && m.containsKey(name)) return+ m[name] = value+ }+ }++ private val roboApp: android.app.Application+ get() = ApplicationProvider.getApplicationContext()++ private var previousTransport: OfficeSync.HttpTransport? = null+ private val rawChannels = mutableMapOf<String, List<String>>()++ private fun channelOf(body: String): String =+ Regex(""""channel":"([^"]+)"""").find(body)?.groupValues?.get(1) ?: ""++ @BeforeTest+ fun setUp() {+ Dispatchers.setMain(UnconfinedTestDispatcher())+ previousTransport = OfficeSync.httpTransport+ OfficeSync.httpTransport = OfficeSync.HttpTransport { url, body ->+ when {+ url.endsWith("/register") -> SimpleResponse(200, "", "{}", emptyMap(), url)+ url.endsWith("/getkey") ->+ SimpleResponse(200, "", Base64.encode(OfficeSync.publicBundle), emptyMap(), url)+ url.endsWith("/append") -> SimpleResponse(200, "", """{"seq":1}""", emptyMap(), url)+ url.endsWith("/pull") -> {+ val actions = rawChannels[channelOf(body)] ?: emptyList()+ val jsonActions = actions.joinToString(",") { "\"$it\"" }+ SimpleResponse(200, "", """{"actions":[$jsonActions],"seq":7}""", emptyMap(), url)+ }+ else -> SimpleResponse(404, "", "", emptyMap(), url)+ }+ }+ runBlocking {+ if (runCatching { OfficeSync.identity }.isFailure) {+ OfficeSync.identity = PqcIdentity.loadOrCreate(MemStore(), "tombstone")+ }+ OfficeSync.init(roboApp)+ }+ }++ @AfterTest+ fun tearDown() {+ OfficeSync.httpTransport = previousTransport+ OfficeSync.stopLive()+ Dispatchers.resetMain()+ // Leave the shared real store as other test classes expect to find+ // it (empty index/requests, no tombstones): these tests seed it.+ runBlocking {+ val ds = realDs()+ ds.setString("officeDocsIndex", "[]")+ ds.setString("officePendingRequests", "[]")+ ds.setString(OfficeDocTombstones.KEY, "[]")+ }+ }++ private fun vm(): OfficeViewModel = OfficeViewModel(roboApp)++ private fun realDs(): DataStoreUtils = DataStoreUtils.getInstance(roboApp)++ private fun loadedVm(text: String): OfficeViewModel {+ val v = vm()+ v.stateMutable.value = OfficeViewModel.ViewState.Loaded(+ OdfDocument.TextDocument(+ title = "Doc",+ content = listOf(+ OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan(text)))))))+ return v+ }++ private fun await(timeoutMs: Long = 10_000, cond: () -> Boolean): Boolean {+ val deadline = System.currentTimeMillis() + timeoutMs+ while (System.currentTimeMillis() < deadline) {+ if (cond()) return true+ Thread.sleep(20)+ }+ return cond()+ }++ /** A signed CRDT op batch for [text], encrypted under [key] like a relay doc action. */+ private fun signedOpBlob(v: OfficeViewModel, text: String, key: ByteArray): String {+ val tree = DocumentTreeCrdt(OfficeSync.deviceId)+ try {+ val opsJson = tree.updateJson(loadedVm(text).exportFlat())+ val sig = Base64.encode(runBlocking { OfficeSync.sign(opsJson.encodeToByteArray()) })+ val signed = v.syncJson.encodeToString(SignedOp(OfficeSync.deviceId, sig, opsJson))+ return Base64.encode(E2ee.aesEncrypt(key, signed.encodeToByteArray()))+ } finally {+ tree.close()+ }+ }++ /** An owner-signed delete record for [docId], encrypted under [key]. */+ private fun signedDeleteBlob(docId: String, key: ByteArray, deletedAt: Long): String {+ val tombstone = OfficeDocTombstone(docId, deletedAt, OfficeSync.deviceId)+ val sig = Base64.encode(+ runBlocking {+ OfficeSync.sign(OfficeDocTombstones.signingBytes(docId, deletedAt))+ },+ )+ val signed = OfficeSync.json.encodeToString(+ SignedDocDelete.serializer(),+ SignedDocDelete(tombstone, sig),+ )+ return Base64.encode(E2ee.aesEncrypt(key, signed.encodeToByteArray()))+ }++ // ---- Pure helpers ----++ @Test+ fun `tombstone helpers round-trip and filter`() {+ val tombstones = listOf(+ OfficeDocTombstone("d1", 100, "dev-a"),+ OfficeDocTombstone("d2", 200, "dev-b"),+ )+ assertEquals(tombstones, OfficeDocTombstones.decode(OfficeDocTombstones.encode(tombstones)))+ assertEquals(emptyList(), OfficeDocTombstones.decode(null))+ assertEquals(emptyList(), OfficeDocTombstones.decode("not json"))+ assertTrue(OfficeDocTombstones.isDeleted(tombstones, "d1"))+ assertFalse(OfficeDocTombstones.isDeleted(tombstones, "d3"))+ // Upsert keeps the newest stamp per doc and never duplicates.+ val older = OfficeDocTombstones.upsert(tombstones, OfficeDocTombstone("d1", 50))+ assertEquals(tombstones, older)+ val newer = OfficeDocTombstones.upsert(tombstones, OfficeDocTombstone("d1", 300))+ assertEquals(2, newer.size)+ assertEquals(300, newer.first { it.docId == "d1" }.deletedAt)+ val metas = listOf(+ OfficeDocMeta(docId = "d1", title = "A", keyB64 = "", owner = true),+ OfficeDocMeta(docId = "d3", title = "C", keyB64 = "", owner = false),+ )+ assertEquals(listOf("d3"), OfficeDocTombstones.filterLive(metas, tombstones).map { it.docId })+ assertEquals(+ "d1|deleted|123",+ OfficeDocTombstones.signingBytes("d1", 123).decodeToString(),+ )+ }++ // ---- Pull paths ----++ @Test+ fun `stale invite pull does not re-add a tombstoned doc`() = runTest {+ val v = vm()+ val ds = realDs()+ v.saveIndex(ds, emptyList())+ v.saveTombstones(ds, listOf(OfficeDocTombstone("doc-tomb-invite", 1_000, "owner-dev")))+ // The fake relay's inbox holds two sealed invites: one for the+ // deleted doc (stale replay), one for a live doc (control).+ val inviteJson = { docId: String ->+ OfficeSync.json.encodeToString(+ OfficeSync.Invite.serializer(),+ OfficeSync.Invite(+ docId = docId,+ key = Base64.encode(ByteArray(32) { 4 }),+ title = "T-$docId",+ ),+ )+ }+ val sealed = listOf("doc-tomb-invite", "doc-tomb-live").map { docId ->+ Base64.encode(runBlocking { OfficeSync.seal(OfficeSync.publicBundle, inviteJson(docId).encodeToByteArray()) })+ }+ rawChannels["inbox:${OfficeSync.deviceId}"] = sealed++ val res = v.pullInboxInvites(ds)+ assertNotNull(res)+ assertEquals(2, res.invites.size)+ // Only the live doc was added; the tombstoned one stays deleted.+ assertEquals(listOf("doc-tomb-live"), v.loadIndex(ds).map { it.docId })+ }++ @Test+ fun `owner tombstone on pull blocks open and stale ops do not resurrect`() = runTest {+ val v = vm()+ val ds = realDs()+ val docId = "doc-tomb-open"+ val key = ByteArray(32) { 31 }+ val meta = OfficeDocMeta(+ docId = docId,+ title = "Doomed",+ keyB64 = Base64.encode(key),+ owner = false,+ role = OfficeRoles.EDITOR,+ ownerKeyB64 = Base64.encode(OfficeSync.publicBundle),+ )+ v.saveIndex(ds, listOf(meta))+ // Relay state: the owner has deleted the doc, but the stale op log+ // (which would rebuild it) is still fully present.+ rawChannels["deleted:$docId"] = listOf(+ signedDeleteBlob(docId, key, System.currentTimeMillis()),+ )+ rawChannels[docId] = listOf(signedOpBlob(v, "zombie text", key))++ v.openOnlineDocument(meta)++ assertTrue(+ await(12_000) { v.state.value is OfficeViewModel.ViewState.Error },+ "state was ${v.state.value}",+ )+ val message = (v.state.value as OfficeViewModel.ViewState.Error).message+ assertTrue(message.contains("deleted"), message)+ // The tombstone was recorded, the index entry dropped, and the doc+ // was never loaded from its stale ops.+ assertTrue(v.loadIndex(ds).none { it.docId == docId })+ assertTrue(v.isDocTombstoned(ds, docId))+ assertFalse(v.state.value is OfficeViewModel.ViewState.Loaded)+ }++ @Test+ fun `syncDoc is a no-op for a tombstoned doc`() = runTest {+ val v = loadedVm("should not sync")+ val ds = realDs()+ val docId = "doc-tomb-sync"+ v.saveTombstones(ds, listOf(OfficeDocTombstone(docId, 5_000, "dev")))+ v.currentRole = OfficeRoles.EDITOR+ v.currentTree = null+ v.syncDoc(docId, ByteArray(32) { 9 })+ // No tree was adopted/created, nothing was queued or persisted.+ assertNull(v.currentTree)+ assertTrue(v.loadPendingOps(ds, docId).isEmpty())+ assertNull(ds.getString("crdt:$docId"))+ }++ @Test+ fun `deleteOnlineDocument records tombstone and drops local state`() = runTest {+ val v = vm()+ val ds = realDs()+ val docId = "doc-tomb-delete"+ val key = ByteArray(32) { 17 }+ ds.setString("crdt:$docId", "seeded-tree")+ ds.setLong("crdtCursor:$docId", 3)+ v.saveTombstones(ds, emptyList())+ v.saveIndex(+ ds,+ listOf(+ OfficeDocMeta(+ docId = docId,+ title = "Mine",+ keyB64 = Base64.encode(key),+ owner = true,+ ownerKeyB64 = Base64.encode(OfficeSync.publicBundle),+ ),+ ),+ )+ val latch = CountDownLatch(1)+ var ok: Boolean? = null+ v.deleteOnlineDocument(docId) { ok = it; latch.countDown() }+ assertTrue(latch.await(10, TimeUnit.SECONDS), "delete callback")+ assertEquals(true, ok)+ assertTrue(await { v.isDocTombstoned(ds, docId) })+ assertTrue(v.loadIndex(ds).none { it.docId == docId })+ assertNull(ds.getString("crdt:$docId"))+ assertNull(ds.getLong("crdtCursor:$docId"))+ }++ @Test+ fun `forged delete record is not honoured`() = runTest {+ val v = vm()+ val ds = realDs()+ val docId = "doc-tomb-forged"+ val key = ByteArray(32) { 23 }+ // Signed over different bytes than it carries: verification fails,+ // so fetch reports "unknown" instead of a tombstone.+ val tombstone = OfficeDocTombstone(docId, 9_999, "attacker")+ val badSig = Base64.encode(+ runBlocking { OfficeSync.sign("something else".encodeToByteArray()) },+ )+ val signed = OfficeSync.json.encodeToString(+ SignedDocDelete.serializer(),+ SignedDocDelete(tombstone, badSig),+ )+ rawChannels["deleted:$docId"] = listOf(+ Base64.encode(E2ee.aesEncrypt(key, signed.encodeToByteArray())),+ )+ assertNull(v.fetchDocDelete(docId, key, OfficeSync.publicBundle))+ assertFalse(v.isDocTombstoned(ds, docId))+ }+}