SyncGenerationStore.kt

7.2 KB · raw

1package com.peachpasswords.sync23import android.content.Context4import android.content.SharedPreferences5import androidx.security.crypto.EncryptedSharedPreferences6import androidx.security.crypto.MasterKey7import dagger.hilt.android.EntryPointAccessors8import dagger.hilt.android.qualifiers.ApplicationContext9import dagger.hilt.EntryPoint10import dagger.hilt.InstallIn11import dagger.hilt.components.SingletonComponent12import javax.inject.Inject13import javax.inject.Singleton1415/**16 * Storage adapter for the Sync-generation state machine.17 *18 * The record itself lives in plain prefs under a key no legacy build knows, so19 * an older build cannot overwrite it and a Keystore failure cannot masquerade as20 * a trust reset. Everything it *reads* — the paired registry, the terminal21 * ledger, known-key history, pending holders — comes from the real stores,22 * because those are Keystore-encrypted and a plain re-read of their file would23 * silently see nothing.24 */25@Singleton26class SyncGenerationStore @Inject constructor(27    @ApplicationContext private val context: Context,28    private val devices: PairedDeviceStore,29    private val pendingDevices: PendingVouchedDeviceStore,30    private val lockedSyncSpool: LockedSyncSpoolStore,31) : SyncGenerationPort {3233    private val generationPrefs =34        context.getSharedPreferences(GENERATION_PREFS_FILE, Context.MODE_PRIVATE)3536    override fun readBlob(): String? = generationPrefs.getString(KEY_GENERATION, null)3738    override fun writeBlob(blob: String): Boolean =39        generationPrefs.edit().putString(KEY_GENERATION, blob).commit() && readBlob() == blob4041    override fun hasPairedDevices(): Boolean = devices.getAll().isNotEmpty()4243    override fun hasRevocations(): Boolean = devices.listRevocations().isNotEmpty()4445    override fun hasIssuerSigningKeys(): Boolean = devices.hasIssuerSigningKeys()4647    override fun hasPendingVouchedDevices(): Boolean = pendingDevices.getAll().isNotEmpty()4849    /**50     * Copy the legacy trust material verbatim into an archive tagged with its51     * generation. Encrypted with the same construction as its source: the52     * registry carries per-pair rendezvous secrets, so a plaintext archive would53     * downgrade them at rest.54     *55     * One fixed file, with the generation in every key: Android's backup rules56     * take literal paths only, so a per-generation filename could not be57     * excluded from cloud backup and device transfer.58     */59    override fun archiveLegacyState(generation: Int): String? = runCatching {60        val archive = encryptedPrefs(context, ARCHIVE_PREFS_FILE)61        val prefix = "g$generation:"62        val expected = buildMap<String, Any?> {63            put("${prefix}meta", """{"schemaVersion":1,"generation":$generation,"archivedAt":${System.currentTimeMillis()}}""")64            for ((key, value) in devices.snapshot()) put("$prefix$ARCHIVE_DEVICES_PREFIX$key", value)65            for ((key, value) in pendingDevices.snapshot()) put("$prefix$ARCHIVE_PENDING_PREFIX$key", value)66        }67        check(archiveTrustPreferenceValues(archive, expected)) { "generation_archive_persist_failed" }68        ARCHIVE_PREFS_FILE69    }.getOrNull()7071    override fun clearLegacyTrustState(): Boolean = runCatching {72        PeachSyncService.stop(context)73        lockedSyncSpool.clear()74        devices.clear()75        pendingDevices.clear()76        devices.getAll().isEmpty() && devices.listRevocations().isEmpty() &&77            !devices.hasIssuerSigningKeys() && pendingDevices.getAll().isEmpty()78    }.getOrDefault(false)7980    /**81     * The reset's identity step (§11.3). Only reached at RESET_CONFIRMED, after82     * the legacy trust has been archived and cleared, so minting here is the83     * anchored device's own deliberate action rather than a silent replacement.84     * The guard still refuses to mint over live trust, which is what would85     * otherwise turn the create-on-miss refusal into a bypass.86     */87    override fun ensureV2Identity(): Boolean = runCatching {88        loadOrCreateLocalIdentity(context)89        true90    }.recoverCatching {91        check(!hasLegacyTrustState()) { "identity_mint_over_live_trust" }92        rotateDeviceId(context)93        true94    }.getOrDefault(false)9596    override fun localDeviceId(): String? =97        runCatching { loadOrCreateLocalIdentity(context).deviceId }.getOrNull()9899    /** Forget the generation record: only a genuinely destroyed vault reaches this. */100    fun clear() {101        generationPrefs.edit().clear().commit()102    }103104    private companion object {105        const val GENERATION_PREFS_FILE = "peach_sync_generation_v1"106        const val ARCHIVE_PREFS_FILE = "peach_sync_archive_v1"107        const val KEY_GENERATION = "sync_generation"108        const val ARCHIVE_DEVICES_PREFIX = "paired:"109        const val ARCHIVE_PENDING_PREFIX = "pending:"110    }111}112113/**114 * [loadOrCreateLocalIdentity] is called from services and screens that hold no115 * injector, so the singleton is fetched here the same way [PeachSyncService]116 * fetches its outcome store.117 */118internal fun syncGenerationStore(context: Context): SyncGenerationStore =119    EntryPointAccessors120        .fromApplication(context.applicationContext, SyncGenerationEntryPoint::class.java)121        .syncGenerationStore()122123@EntryPoint124@InstallIn(SingletonComponent::class)125internal interface SyncGenerationEntryPoint {126    fun syncGenerationStore(): SyncGenerationStore127}128129private fun encryptedPrefs(context: Context, name: String): SharedPreferences =130    EncryptedSharedPreferences.create(131        context,132        name,133        MasterKey.Builder(context).setKeyScheme(MasterKey.KeyScheme.AES256_GCM).build(),134        EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,135        EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM,136    )137138internal fun copyRawTrustPreferences(values: Map<String, *>): Map<String, Any> = values.mapValues { (key, value) ->139    when (value) {140        is String, is Int, is Long, is Float, is Boolean -> value141        is Set<*> -> value.map { item ->142            require(item is String) { "unsupported_trust_preference:$key" }143            item144        }.toSet()145        else -> throw IllegalArgumentException("unsupported_trust_preference:$key")146    }147}148149internal fun putRawTrustPreferences(edit: SharedPreferences.Editor, values: Map<String, Any>) {150    values.forEach { (key, value) ->151        when (value) {152            is String -> edit.putString(key, value)153            is Int -> edit.putInt(key, value)154            is Long -> edit.putLong(key, value)155            is Float -> edit.putFloat(key, value)156            is Boolean -> edit.putBoolean(key, value)157            is Set<*> -> edit.putStringSet(key, value.map { item ->158                require(item is String) { "unsupported_trust_preference:$key" }159                item160            }.toSet())161            else -> throw IllegalArgumentException("unsupported_trust_preference:$key")162        }163    }164}165166internal fun archiveTrustPreferenceValues(archive: SharedPreferences, expected: Map<String, Any?>): Boolean {167    val raw = copyRawTrustPreferences(expected)168    val edit = archive.edit()169    putRawTrustPreferences(edit, raw)170    if (!edit.commit()) return false171    val actual = archive.all172    return raw.all { (key, value) -> actual[key] == value }173}