PendingVouchedDeviceStore.kt

7.2 KB · raw

1package com.peachpasswords.sync23import android.content.Context4import androidx.security.crypto.EncryptedSharedPreferences5import androidx.security.crypto.MasterKey6import dagger.hilt.android.qualifiers.ApplicationContext7import kotlinx.coroutines.channels.awaitClose8import kotlinx.coroutines.flow.Flow9import kotlinx.coroutines.flow.callbackFlow10import kotlinx.serialization.Serializable11import kotlinx.serialization.builtins.ListSerializer12import kotlinx.serialization.json.Json13import javax.inject.Inject14import javax.inject.Singleton1516@Serializable17data class PendingVouchedDevice(18    val deviceId: String,19    val deviceName: String,20    val deviceType: String,21    val longTermPublicKeyHex: String,22    val signingPublicKeyHex: String,23    val wsPort: Int? = null,24    val pairedAt: Long,25    val receivedAt: Long,26    val vouchedByDeviceId: String,27)2829interface PendingVouchedRegistry {30    fun getAll(): List<PendingVouchedDevice>31    fun upsert(device: PendingVouchedDevice)32    /** Persist one pending introduction and report whether the durable commit succeeded. */33    fun upsertAndReport(device: PendingVouchedDevice): Boolean {34        return runCatching {35            upsert(device)36            true37        }.getOrDefault(false)38    }39    /**40     * Remove one pending introduction and report whether the durable commit41     * succeeded. The default preserves compatibility for in-memory registries42     * that only implement the legacy void removal API.43     */44    fun removeAndReport(id: String): Boolean {45        return runCatching {46            remove(id)47            true48        }.getOrDefault(false)49    }5051    /** Legacy removal API retained for existing registry callers. */52    fun remove(id: String)5354    /**55     * Remove a set of pending introductions synchronously and report failure.56     * Implementations must linearize the whole batch; the default exists only57     * for small in-memory test registries that have no durable store.58     */59    fun removeBatch(ids: Set<String>): Boolean {60        return runCatching {61            ids.forEach(::remove)62            true63        }.getOrDefault(false)64    }6566    /** Restore a previously captured pending set after a later trust commit fails. */67    fun restoreBatch(devices: List<PendingVouchedDevice>): Boolean {68        return runCatching {69            devices.forEach(::upsert)70            true71        }.getOrDefault(false)72    }73}7475@Singleton76class PendingVouchedDeviceStore @Inject constructor(77    @ApplicationContext context: Context,78) : PendingVouchedRegistry {79    private val masterKey = MasterKey.Builder(context)80        .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)81        .build()8283    private val prefs = EncryptedSharedPreferences.create(84        context,85        PREFS_FILE,86        masterKey,87        EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,88        EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM,89    )9091    private val listSerializer = ListSerializer(PendingVouchedDevice.serializer())9293    override fun getAll(): List<PendingVouchedDevice> {94        val raw = prefs.getString(KEY_PENDING, null) ?: return emptyList()95        return runCatching { json.decodeFromString(listSerializer, raw) }.getOrDefault(emptyList())96    }9798    fun get(id: String): PendingVouchedDevice? = getAll().firstOrNull { it.deviceId == id }99100    override fun upsert(device: PendingVouchedDevice) {101        upsertAndReport(device)102    }103104    override fun upsertAndReport(device: PendingVouchedDevice): Boolean {105        // Vouch requests carry a peer-chosen name; bound it like every other106        // inbound name so the pending queue cannot grow without limit.107        val device = device.copy(deviceName = capDeviceName(device.deviceName))108        val next = (getAll().filterNot { it.deviceId == device.deviceId } + device).takeLast(MAX_PENDING)109        return commitList(next)110    }111112    override fun remove(id: String) {113        removeAndReport(id)114    }115116    override fun removeAndReport(id: String): Boolean {117        val before = getAll()118        val after = before.filterNot { it.deviceId == id }119        return commitWithRollback(before, after, ::commitList)120    }121122    /**123     * Remove a set of pending introductions synchronously and report failure.124     * Implementations must linearize the whole batch; the default exists only125     * for small in-memory test registries that have no durable store.126     */127    override fun removeBatch(ids: Set<String>): Boolean {128        if (ids.isEmpty()) return true129        val before = getAll()130        val after = before.filterNot { it.deviceId in ids }131        return commitWithRollback(before, after, ::commitList)132    }133134    override fun restoreBatch(devices: List<PendingVouchedDevice>): Boolean {135        if (devices.isEmpty()) return true136        val before = getAll()137        val restoredIds = devices.map { it.deviceId }.toSet()138        val after = (before.filterNot { it.deviceId in restoredIds } + devices).takeLast(MAX_PENDING)139        return commitWithRollback(before, after, ::commitList)140    }141142    fun clear() {143        persist(emptyList())144    }145146    fun observeAll(): Flow<List<PendingVouchedDevice>> = callbackFlow {147        trySend(getAll())148        val listener = android.content.SharedPreferences.OnSharedPreferenceChangeListener { _, key ->149            if (key == KEY_PENDING || key == null) trySend(getAll())150        }151        prefs.registerOnSharedPreferenceChangeListener(listener)152        awaitClose { prefs.unregisterOnSharedPreferenceChangeListener(listener) }153    }154155    private fun persist(devices: List<PendingVouchedDevice>) {156        prefs.edit()157            .putString(KEY_PENDING, json.encodeToString(listSerializer, devices))158            // Pending introductions participate in fail-closed trust ordering;159            // an outstanding async apply could replay a stale row after a160            // synchronous revocation/removal commit. Keep every write in this161            // store synchronous so removal cannot be overwritten by a queued162            // disk task after a crash.163            .commit()164    }165166    /** Synchronous writer used by the fail-closed batch/rollback paths. */167    private fun commitList(devices: List<PendingVouchedDevice>): Boolean =168        prefs.edit()169            .putString(KEY_PENDING, json.encodeToString(listSerializer, devices))170            .commit()171172    private companion object {173        const val PREFS_FILE = "peach_pending_vouched_devices"174        const val KEY_PENDING = "pending_vouched_devices"175        const val MAX_PENDING = 50176        val json = Json { encodeDefaults = true; ignoreUnknownKeys = true }177    }178}179180/**181 * Apply a durable state transition, explicitly restoring the prior in-process182 * value when the forward commit reports failure. Android's SharedPreferences183 * contract normally leaves the old value in memory on `commit()==false`, but184 * relying on that implementation detail made failure injection indistinguishable185 * from a successful transaction. Both registry stores use this helper.186 */187internal fun <T> commitWithRollback(188    before: T,189    after: T,190    commit: (T) -> Boolean,191): Boolean {192    val applied = runCatching { commit(after) }.getOrDefault(false)193    if (applied) return true194    runCatching { commit(before) }195    return false196}