LockedSyncSpoolStore.kt

9.9 KB · raw

1package com.peachpasswords.sync23import android.content.Context4import androidx.security.crypto.EncryptedSharedPreferences5import androidx.security.crypto.MasterKey6import com.peachpasswords.vault.VaultCrypto7import com.peachpasswords.vault.VaultRepository8import dagger.hilt.android.qualifiers.ApplicationContext9import kotlinx.serialization.Serializable10import kotlinx.serialization.json.Json11import org.bouncycastle.crypto.params.X25519PrivateKeyParameters12import java.security.MessageDigest13import javax.inject.Inject14import javax.inject.Singleton1516@Serializable17internal data class LockedSyncCachedEntry(val modifiedAt: Long, val ciphertext: String)1819@Serializable20internal data class LockedSyncSpool(21    val version: Int = 1,22    val vaultId: String,23    val deviceId: String,24    val deviceName: String,25    val localVersion: Long,26    val longTermPublicKeyHex: String,27    val longTermPrivateKeyHex: String? = null,28    val signingPublicKeyHex: String,29    val entries: Map<String, LockedSyncCachedEntry>,30    val tombstones: Map<String, Long>,31    val inboxEntries: Map<String, LockedSyncCachedEntry> = emptyMap(),32    val inboxTombstones: Map<String, Long> = emptyMap(),33) {34    init {35        require(entries.size <= SyncLimits.MAX_ENTRY_COUNT) { "sync_entry_count_exceeded" }36        require(inboxEntries.size <= SyncLimits.MAX_ENTRY_COUNT) { "sync_entry_count_exceeded" }37        require(tombstones.size <= SyncLimits.MAX_TOMBSTONE_COUNT) { "sync_tombstone_count_exceeded" }38        require(inboxTombstones.size <= SyncLimits.MAX_TOMBSTONE_COUNT) { "sync_tombstone_count_exceeded" }39    }40}4142/** A Keystore-encrypted cache of opaque entry envelopes and transport identity. */43@Singleton44class LockedSyncSpoolStore @Inject constructor(45    @ApplicationContext private val context: Context,46) {47    private val masterKey = MasterKey.Builder(context)48        .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)49        .build()50    private val prefs = EncryptedSharedPreferences.create(51        context,52        PREFS_FILE,53        masterKey,54        EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,55        EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM,56    )5758    @Synchronized59    internal fun refresh(repo: VaultRepository) {60        val snapshot = repo.syncMasterKeySnapshot() ?: return61        val root = snapshot.key62        val deviceId = getOrCreateDeviceId(context)63        val keys = deriveSyncIdentityKeypair(root, deviceId)64        try {65            val prior = read()66            val entries = repo.getEntries().associate { entry ->67                entry.id to LockedSyncCachedEntry(68                    entry.modifiedAt,69                    VaultSyncAdapter.encryptEntryWithMasterKey(root, entry),70                )71            }72            if (!repo.isSessionEpochCurrent(snapshot.epoch)) return73            val signing = deriveSyncSigningKeypair(root, deviceId)74            write(75                LockedSyncSpool(76                    vaultId = computeVaultId(root),77                    deviceId = deviceId,78                    deviceName = getDeviceName(context),79                    localVersion = repo.getVaultVersion(),80                    longTermPublicKeyHex = pubkeyToHex(keys.publicKey),81                    longTermPrivateKeyHex = pubkeyToHex(keys.secretKey),82                    signingPublicKeyHex = pubkeyToHex(signing.publicKeyRaw),83                    entries = entries,84                    tombstones = repo.getTombstones().associate { it.id to it.deletedAt },85                    inboxEntries = prior?.inboxEntries ?: emptyMap(),86                    inboxTombstones = prior?.inboxTombstones ?: emptyMap(),87                ),88            )89        } finally {90            VaultCrypto.zero(root)91            VaultCrypto.zero(keys.secretKey)92        }93    }9495    internal fun identity(): Pair<SyncIdentityKeypair, LocalDeviceIdentity>? {96        val state = read() ?: return null97        return lockedSyncIdentity(state, RelaySettingsStore.readRelayUrl(context))98    }99100    internal fun adapter(): SyncVaultAdapter? = read()?.let { LockedSyncVaultAdapter(this, it.vaultId) }101102    internal suspend fun drainInto(repo: VaultRepository) {103        val staged = read() ?: return104        if (staged.inboxEntries.isNotEmpty() || staged.inboxTombstones.isNotEmpty()) {105            val live = VaultSyncAdapter(repo, staged.deviceId)106            live.applyEntries(107                staged.inboxEntries.mapValues { it.value.ciphertext },108                staged.inboxEntries.mapValues { it.value.modifiedAt },109            )110            live.applyTombstones(staged.inboxTombstones)111            synchronized(this) {112                val current = read() ?: return@synchronized113                write(114                    current.copy(115                        inboxEntries = current.inboxEntries.filter { (id, value) ->116                            staged.inboxEntries[id]?.ciphertext != value.ciphertext117                        },118                        inboxTombstones = current.inboxTombstones.filter { (id, value) ->119                            staged.inboxTombstones[id] != value120                        },121                    ),122                )123            }124        }125        refresh(repo)126    }127128    @Synchronized129    internal fun stageEntries(vaultId: String, entries: Map<String, String>, manifest: Map<String, Long>) {130        val current = read()?.takeIf { it.vaultId == vaultId } ?: return131        require(entries.size <= SyncLimits.MAX_ENTRY_COUNT) { "sync_entry_count_exceeded" }132        val now = System.currentTimeMillis()133        val inbox = current.inboxEntries.toMutableMap()134        entries.forEach { (id, ciphertext) ->135            val claimed = manifest[id] ?: return@forEach136            if (claimed <= 0L || ciphertext.length > SyncLimits.MAX_ENTRY_ENVELOPE_BYTES) return@forEach137            val modifiedAt = SyncLimits.clampSyncTimestamp(claimed, now)138            if ((inbox[id]?.modifiedAt ?: 0L) < modifiedAt) {139                inbox[id] = LockedSyncCachedEntry(modifiedAt, ciphertext)140            }141        }142        write(current.copy(inboxEntries = inbox))143    }144145    @Synchronized146    internal fun stageTombstones(vaultId: String, tombstones: Map<String, Long>) {147        val current = read()?.takeIf { it.vaultId == vaultId } ?: return148        require(tombstones.size <= SyncLimits.MAX_TOMBSTONE_COUNT) { "sync_tombstone_count_exceeded" }149        val now = System.currentTimeMillis()150        val inbox = current.inboxTombstones.toMutableMap()151        tombstones.forEach { (id, timestamp) ->152            if (timestamp <= 0L) return@forEach153            val deletedAt = SyncLimits.clampSyncTimestamp(timestamp, now)154            if ((inbox[id] ?: 0L) < deletedAt) inbox[id] = deletedAt155        }156        write(current.copy(inboxTombstones = inbox))157    }158159    internal fun snapshot(vaultId: String): LockedSyncSpool? = read()?.takeIf { it.vaultId == vaultId }160    fun clear() { prefs.edit().remove(KEY_STATE).commit() }161162    private fun read(): LockedSyncSpool? {163        val raw = prefs.getString(KEY_STATE, null) ?: return null164        return runCatching { json.decodeFromString(LockedSyncSpool.serializer(), raw) }165            .getOrNull()166            ?.takeIf { it.version == 1 && it.vaultId.matches(Regex("^[0-9a-f]{64}$")) }167    }168169    private fun write(state: LockedSyncSpool) {170        check(prefs.edit().putString(KEY_STATE, json.encodeToString(LockedSyncSpool.serializer(), state)).commit()) {171            "locked_sync_spool_write_failed"172        }173    }174175    private companion object {176        const val PREFS_FILE = "peach_locked_sync_spool_v1"177        const val KEY_STATE = "state"178        val json = Json { encodeDefaults = true; ignoreUnknownKeys = true }179    }180}181182internal fun lockedSyncIdentity(183    state: LockedSyncSpool,184    relayUrl: String,185): Pair<SyncIdentityKeypair, LocalDeviceIdentity>? {186    val privateHex = state.longTermPrivateKeyHex ?: return null187    val secret = runCatching { hexToBytes(privateHex) }.getOrNull() ?: return null188    if (secret.size != 32) {189        VaultCrypto.zero(secret)190        return null191    }192    return try {193        val public = X25519PrivateKeyParameters(secret, 0).generatePublicKey().encoded194        val expectedPublic = hexToPubkey(state.longTermPublicKeyHex)195        if (!MessageDigest.isEqual(public, expectedPublic)) {196            VaultCrypto.zero(public)197            VaultCrypto.zero(secret)198            null199        } else {200            SyncIdentityKeypair(public, secret) to LocalDeviceIdentity(201                deviceId = state.deviceId,202                deviceName = state.deviceName,203                deviceType = DeviceType.ANDROID,204                longTermPublicKeyHex = state.longTermPublicKeyHex,205                signingPublicKeyHex = state.signingPublicKeyHex,206                relayUrl = relayUrl,207            )208        }209    } catch (_: RuntimeException) {210        VaultCrypto.zero(secret)211        null212    }213}214215internal class LockedSyncVaultAdapter(216    private val store: LockedSyncSpoolStore,217    private val vaultId: String,218) : SyncVaultAdapter {219    private fun state() = store.snapshot(vaultId) ?: throw VaultLockedException()220    override suspend fun computeVaultId() = vaultId221    override suspend fun getOurDeviceId() = state().deviceId222    override suspend fun getLocalVersion() = state().localVersion223    override suspend fun buildEntryManifest() = state().entries.mapValues { it.value.modifiedAt }224    override suspend fun buildTombstoneManifest() = state().tombstones225    override suspend fun getEncryptedEntries(entryIds: List<String>): Map<String, String> {226        val entries = state().entries227        return entryIds.mapNotNull { id -> entries[id]?.ciphertext?.let { id to it } }.toMap()228    }229    override suspend fun applyEntries(entries: Map<String, String>, remoteManifest: Map<String, Long>) =230        store.stageEntries(vaultId, entries, remoteManifest)231    override suspend fun applyTombstones(tombstones: Map<String, Long>) =232        store.stageTombstones(vaultId, tombstones)233}234235internal object LockedSyncSpoolHooks {236    @Volatile var refresh: (VaultRepository) -> Unit = {}237}