VaultSyncAdapter.kt

21.4 KB · raw

1package com.peachpasswords.sync23import com.peachpasswords.vault.Tombstone4import com.peachpasswords.vault.VaultCrypto5import com.peachpasswords.vault.VaultEntry6import com.peachpasswords.vault.VaultRepository7import kotlinx.serialization.json.Json8import org.bouncycastle.crypto.digests.SHA256Digest9import org.bouncycastle.crypto.generators.HKDFBytesGenerator10import org.bouncycastle.crypto.params.HKDFParameters11import java.security.SecureRandom12import java.util.Base6413import javax.crypto.Cipher14import javax.crypto.spec.GCMParameterSpec15import javax.crypto.spec.SecretKeySpec1617/**18 * Production [SyncVaultAdapter] backing the coordinator with the live19 * [VaultRepository]. Exact port of the browser `sync-vault-adapter.ts`:20 * the coordinator only ever moves opaque base64 envelopes; plaintext crosses21 * this boundary and nowhere else.22 *23 * Envelope cipher: AES-GCM under a PER-ENTRY key24 *   HKDF-SHA256(ikm = syncMasterKey, salt = "", info = entryId + "\u0000" + "sync-entry-v1")25 * with a random 12-byte nonce and aad = "peach-sync-entry-v1". Binding the key26 * to the entry id means a ciphertext minted for one slot cannot be replayed27 * into another — [applyEntries] rejects any envelope whose decrypted id does28 * not match the map key it arrived under. Both paired devices hold the same29 * syncMasterKey (same vault root key), so keys match without negotiation; the30 * Noise KK reconnect session is a second, independent encryption layer on top.31 */32class VaultSyncAdapter(33    private val repo: VaultRepository,34    private val ourDeviceId: String,35    private val pairedDevices: PairedDeviceRegistry? = null,36    private val pendingVouched: PendingVouchedRegistry? = null,37    private val syncAlerts: SyncAlertRecorder? = null,38    private var remoteDeviceName: String = "paired device",39    override val supportsDeviceManifest: Boolean = pairedDevices != null && pendingVouched != null,40    private val localCredentials: LocalIdentityCredentials? = null,41) : SyncVaultAdapter {4243    override suspend fun computeVaultId(): String =44        repo.syncVaultId() ?: throw VaultLockedException()4546    override suspend fun getOurDeviceId(): String = ourDeviceId4748    override suspend fun getLocalVersion(): Long = repo.getVaultVersion()4950    override suspend fun buildEntryManifest(): Map<String, Long> {51        val snapshot = requireMasterKeySnapshot()52        VaultCrypto.zero(snapshot.key)53        val manifest = repo.getEntries().associate { it.id to it.modifiedAt }54        if (!repo.isSessionEpochCurrent(snapshot.epoch)) throw VaultLockedException()55        return manifest56    }5758    override suspend fun buildTombstoneManifest(): Map<String, Long> {59        val snapshot = requireMasterKeySnapshot()60        VaultCrypto.zero(snapshot.key)61        val manifest = repo.getTombstones().associate { it.id to it.deletedAt }62        if (!repo.isSessionEpochCurrent(snapshot.epoch)) throw VaultLockedException()63        return manifest64    }6566    override suspend fun getEncryptedEntries(entryIds: List<String>): Map<String, String> {67        val snapshot = requireMasterKeySnapshot()68        val master = snapshot.key69        try {70            val out = LinkedHashMap<String, String>()71            for (id in entryIds) {72                val entry = repo.getEntry(id) ?: continue73                // M-05: deriveEntryKey materializes a per-entry 32-byte key that74                // never leaves this loop; zero it after encrypt so the GC copy75                // doesn't outlive the ciphertext.76                var entryKey: ByteArray? = null77                try {78                    entryKey = deriveEntryKey(master, id)79                    out[id] = encryptEntry(entryKey, entry)80                } finally {81                    entryKey?.let(VaultCrypto::zero)82                }83            }84            if (!repo.isSessionEpochCurrent(snapshot.epoch)) throw VaultLockedException()85            return out86        } finally {87            VaultCrypto.zero(master)88        }89    }9091    override suspend fun applyEntries(92        entries: Map<String, String>,93        remoteManifest: Map<String, Long>,94    ) {95        val snapshot = requireMasterKeySnapshot()96        val master = snapshot.key97        val decrypted = try {98            entries.mapNotNull { (id, envelope) ->99                // M-05: per-entry derived key is used exactly once below; zero it100                // after the decrypt so it doesn't sit on the heap alongside the101                // plaintext VaultEntry we're about to commit.102                var entryKey: ByteArray? = null103                val entry = try {104                    entryKey = deriveEntryKey(master, id)105                    decryptEntryOrNull(entryKey, envelope)106                } finally {107                    entryKey?.let(VaultCrypto::zero)108                }109                // The map key is the authority on id — refuse a swapped envelope110                // so a ciphertext can't poison a different entry slot.111                if (entry != null && entry.id == id) entry else null112            }113        } finally {114            VaultCrypto.zero(master)115        }116        if (decrypted.isNotEmpty()) {117            repo.applyMergedRemoteEntries(decrypted, emptyList(), expectedEpoch = snapshot.epoch)118        }119    }120121    override suspend fun applyTombstones(tombstones: Map<String, Long>) {122        val cleaned = tombstones123            .filterValues { it > 0L }124            .map { (id, ts) -> Tombstone(id, ts) }125        if (cleaned.isNotEmpty()) {126            val snapshot = requireMasterKeySnapshot()127            VaultCrypto.zero(snapshot.key)128            repo.applyMergedRemoteEntries(emptyList(), cleaned, expectedEpoch = snapshot.epoch)129        }130    }131132    override fun bindAuthenticatedPeer(peer: PairedDevice) {133        remoteDeviceName = peer.deviceName?.takeIf { it.isNotBlank() }134            ?: peer.deviceId.takeIf { it.isNotBlank() }135            ?: "paired device"136    }137138    override suspend fun buildOutgoingDeviceManifest(): SignedDeviceManifest? {139        val registry = pairedDevices ?: return null140        val signing = localCredentials?.let(::localSigningKeypair)141            ?: throw IllegalStateException("identity_migration_required")142        val revoked = registry.listRevocations()143        val revokedIds = revoked.map { it.deviceId }.toSet()144        val devices = registry.getAll()145            .filterNot { revokedIds.contains(it.deviceId) }146            .mapNotNull { it.toManifestEntry() }147            .map { it.copy(vouchDepth = if (it.deviceId == ourDeviceId) 0 else it.vouchDepth + 1) }148        return buildSignedDeviceManifest(ourDeviceId, devices, signing.privateKey, revoked = revoked)149    }150151    override suspend fun applyIncomingDeviceManifest(152        manifest: SignedDeviceManifest,153        authenticatedRemoteStaticPublicKey: ByteArray,154    ) {155        val registry = pairedDevices ?: return156        val pending = pendingVouched ?: return157        if (authenticatedRemoteStaticPublicKey.size != 32) return158        if (manifest.body.revoked.size > MAX_MANIFEST_REVOCATIONS ||159            manifest.body.revoked.any { it.revokedByDeviceId.length > MAX_MANIFEST_STRING }160        ) return161        val registrySnapshot = registry.manifestSnapshot(manifest.body.revoked.map { it.revokedByDeviceId }.toSet())162        val currentById = registrySnapshot.devices.associateBy { it.deviceId }163        val remoteStatic = pubkeyToHex(authenticatedRemoteStaticPublicKey)164        val issuer = registrySnapshot.devices.firstOrNull {165            it.longTermPublicKeyHex?.let { key -> CryptoCompare.hex(key, remoteStatic) } == true166        } ?: return167        // Direct and bounded-vouch issuers may propagate the signed device pool.168        if (issuer.trustSource != "direct" && issuer.trustSource != "vouched") return169        if (issuer.vouchDepth >= MAX_VOUCH_DEPTH) return170        val currentSigningKey = issuer.signingPublicKeyHex?.lowercase()?.takeIf { it.length == 64 } ?: return171        val knownIssuerKeys = registrySnapshot.issuerSigningKeys[issuer.deviceId].orEmpty() + currentSigningKey172        // Historical keys and the persisted current key remain valid; mutable173        // device metadata never rewrites the issuer's key history.174        //175        // A revocation may name any device as its issuer — including one whose176        // active row is gone — so resolve that issuer's key from the registry177        // and its immutable history rather than from the record itself.178        val resolveIssuerSigningKeys: (String) -> Set<String> = { deviceId ->179            val history = registrySnapshot.issuerSigningKeys[deviceId].orEmpty()180            val current = currentById[deviceId]?.signingPublicKeyHex?.lowercase()181            if (current != null && current.length == 64) history + current else history182        }183        val verified = knownIssuerKeys.firstNotNullOfOrNull { candidate ->184            runCatching {185                verifyDeviceManifest(manifest, hexToPubkey(candidate), resolveIssuerSigningKeys)186                    ?.let { candidate to it }187            }.getOrNull()188        } ?: return189        val (signingKey, body) = verified190        if (body.issuerDeviceId != issuer.deviceId) return191        val snapshot = requireMasterKeySnapshot()192        val master = snapshot.key193        val localKeys = localCredentials?.let(::localSyncKeypair)194            ?: throw IllegalStateException("identity_migration_required")195        try {196            if (!repo.isSessionEpochCurrent(snapshot.epoch)) return197            // Stage the complete result against one read-only registry snapshot.198            // No registry mutation is allowed until the epoch-fenced batch below;199            // a per-item epoch check would still leave a prefix behind if lock()200            // wins between two items.201            val incomingRevocations = body.revoked.filterNot { it.deviceId == ourDeviceId }202            val currentRevocations = registrySnapshot.revocations203            val knownRevokedIds = currentRevocations.map { it.deviceId }.toSet()204            val newlyRevoked = incomingRevocations.filterNot { knownRevokedIds.contains(it.deviceId) }205            val revokedIds = (knownRevokedIds + incomingRevocations.map { it.deviceId }).toSet()206            val revokedKeys = (currentRevocations + incomingRevocations)207                .map { it.longTermPublicKeyHex.lowercase() }208                .filterNot { it == NO_KEY_SENTINEL }209                .toSet()210            fun revokedInStagedBatch(deviceId: String, longTermKey: String): Boolean {211                return deviceId in revokedIds || longTermKey.lowercase() in revokedKeys212            }213214            val stagedUpserts = LinkedHashMap<String, PairedDevice>()215            val stagedAlerts = ArrayList<SyncAlert>()216            newlyRevoked.forEach { revocation ->217                stagedAlerts += SyncAlert(218                    type = SyncAlertType.DEVICE_REVOKED,219                    deviceName = issuer.deviceName ?: "paired device",220                    entryTitle = revocation.deviceId,221                    timestamp = System.currentTimeMillis(),222                )223            }224            for (entry in body.devices) {225                if (entry.deviceId == ourDeviceId || entry.deviceId == issuer.deviceId) {226                    continue227                }228                if (revokedInStagedBatch(entry.deviceId, entry.longTermPublicKeyHex)) {229                    continue230                }231                if (entry.vouchDepth > issuer.vouchDepth + 1) continue232                val existing = stagedUpserts[entry.deviceId] ?: currentById[entry.deviceId]233                val meshRoute = deriveManifestMeshRoute(localKeys.secretKey, localKeys.publicKey, entry)234                if (existing == null) {235                    if (meshRoute == null) continue236                    stagedUpserts[entry.deviceId] = PairedDevice(237                        deviceId = entry.deviceId,238                        deviceName = entry.deviceName,239                        deviceType = entry.deviceType,240                        longTermPublicKeyHex = entry.longTermPublicKeyHex.lowercase(),241                        signingPublicKeyHex = entry.signingPublicKeyHex.lowercase(),242                        trustSource = "vouched",243                        vouchDepth = issuer.vouchDepth + 1,244                        wsPort = entry.wsPort,245                        rendezvousSecretHex = meshRoute.first,246                        relayUrl = meshRoute.second,247                        pairedAt = entry.pairedAt,248                    )249                } else {250                    val incomingLongTermKey = entry.longTermPublicKeyHex.lowercase()251                    val incomingSigningKey = entry.signingPublicKeyHex.lowercase()252                    // Direct pairing is SAS-pinned. A manifest issuer is never253                    // authorized to rotate either identity key, even if the254                    // entry is correctly vouched and the manifest verifies.255                    // Drop the entry wholesale rather than retaining mutable256                    // metadata alongside an untrusted identity transition.257                    val longTermChanged = existing.longTermPublicKeyHex?.let {258                        !CryptoCompare.hex(it, incomingLongTermKey)259                    } == true260                    val signingChanged = existing.signingPublicKeyHex?.let {261                        !CryptoCompare.hex(it, incomingSigningKey)262                    } == true263                    if (longTermChanged || signingChanged) {264                        deviceKeyRotationAlert(existing, entry, System.currentTimeMillis())265                            ?.let(stagedAlerts::add)266                        continue267                    }268                    deviceKeyRotationAlert(existing, entry, System.currentTimeMillis())?.let(stagedAlerts::add)269                    stagedUpserts[entry.deviceId] = existing.copy(270                        deviceName = existing.deviceName?.takeIf { it.isNotBlank() }271                            ?: entry.deviceName,272                        deviceType = entry.deviceType,273                        // Every admitted identity is immutable. Only an explicit,274                        // physically confirmed re-pair may replace these keys.275                        longTermPublicKeyHex = existing.longTermPublicKeyHex ?: incomingLongTermKey,276                        signingPublicKeyHex = existing.signingPublicKeyHex ?: incomingSigningKey,277                        vouchDepth = entry.vouchDepth,278                        wsPort = existing.wsPort ?: entry.wsPort,279                        rendezvousSecretHex =280                            if (existing.trustSource == "vouched" && meshRoute != null) {281                                meshRoute.first282                            } else {283                                existing.rendezvousSecretHex284                            },285                        relayUrl =286                            if (existing.trustSource == "vouched" && meshRoute != null) {287                                meshRoute.second288                            } else {289                                existing.relayUrl290                            },291                        pairedAt = existing.pairedAt,292                        trustSource = existing.trustSource,293                    )294                }295            }296297            val batch = DeviceManifestRegistryBatch(298                incomingRevocations = incomingRevocations,299                removals = newlyRevoked.map { it.deviceId }.toSet(),300                upserts = stagedUpserts.values.toList(),301                issuerSigningKeys = mapOf(issuer.deviceId to setOf(signingKey)),302                expectedSnapshot = registrySnapshot,303                authenticatedIssuer = DeviceManifestIssuerBinding(304                    issuer.deviceId,305                    issuer.longTermPublicKeyHex ?: return,306                    currentSigningKey,307                ),308            )309            // Remove any matching pending introductions synchronously BEFORE310            // installing trust. If the registry commit fails, restoring this311            // exact pending subset is safe; if restoration also fails, the312            // fail-closed outcome is a lost introduction, never stale trust.313            val pendingIds = batch.removals + stagedUpserts.keys314            val priorPending = pending.getAll().filter { it.deviceId in pendingIds }315            val committed = repo.withSessionEpochCommit(snapshot.epoch) {316                val pendingRemoved = runCatching { pending.removeBatch(pendingIds) }.getOrDefault(false)317                if (!pendingRemoved) {318                    pending.restoreBatch(priorPending)319                    false320                } else {321                    val registryCommitted = runCatching { registry.applyManifestBatch(batch) }.getOrDefault(false)322                    if (registryCommitted) {323                        // Pending entries and alerts are kept inside the same324                        // epoch fence. Alerts follow the trust commit and never325                        // participate in its semantics.326                        if (stagedAlerts.isNotEmpty()) syncAlerts?.record(stagedAlerts)327                        true328                    } else {329                        pending.restoreBatch(priorPending)330                        false331                    }332                }333            }334            if (committed != true) return335        } finally {336            VaultCrypto.zero(master)337            VaultCrypto.zero(localKeys.secretKey)338        }339    }340341    private fun deriveManifestMeshRoute(342        localPrivateKey: ByteArray,343        localPublicKey: ByteArray,344        entry: ManifestDeviceEntry,345    ): Pair<String, String>? = runCatching {346        val relayUrl = Rendezvous.normalizeRelayUrl(entry.relayUrl ?: return null)347        val secret = Rendezvous.deriveMeshSecret(348            localPrivateKey,349            localPublicKey,350            hexToPubkey(entry.longTermPublicKeyHex),351        )352        try {353            Rendezvous.bytesToHex(secret) to relayUrl354        } finally {355            VaultCrypto.zero(secret)356        }357    }.getOrNull()358359    private fun requireMasterKeySnapshot(): VaultRepository.SyncMasterKeySnapshot =360        repo.syncMasterKeySnapshot() ?: throw VaultLockedException()361362    internal companion object {363        internal fun deriveEntryKey(masterKey: ByteArray, entryId: String): ByteArray {364            // Null-byte separator (HKDF hardening): entryId cannot contain U+0000, so365            // the (entryId, suffix) boundary is unambiguous regardless of future id366            // formats. Coordinated wire change — peach-browser deriveEntryKey produces367            // the identical info bytes; the two MUST stay byte-for-byte in lockstep.368            val info = (entryId + "\u0000" + ENTRY_KEY_INFO_SUFFIX).toByteArray(Charsets.UTF_8)369            val gen = HKDFBytesGenerator(SHA256Digest())370            gen.init(HKDFParameters(masterKey, ByteArray(0), info))371            return ByteArray(32).also { gen.generateBytes(it, 0, it.size) }372        }373374        internal fun encryptEntry(key: ByteArray, entry: VaultEntry): String {375            // M-05: plaintext is the entry JSON (incl. password field). Zero in376            // finally so the serialized copy doesn't outlive the ciphertext.377            var plaintext: ByteArray? = null378            return try {379                plaintext = entryJson.encodeToString(VaultEntry.serializer(), entry).toByteArray(Charsets.UTF_8)380                val nonce = ByteArray(12).also(rng::nextBytes)381                val cipher = Cipher.getInstance("AES/GCM/NoPadding")382                cipher.init(Cipher.ENCRYPT_MODE, SecretKeySpec(key, "AES"), GCMParameterSpec(128, nonce))383                cipher.updateAAD(ENTRY_AAD)384                val ct = cipher.doFinal(plaintext)385                b64(nonce + ct)386            } finally {387                plaintext?.let(VaultCrypto::zero)388            }389        }390391        internal fun encryptEntryWithMasterKey(masterKey: ByteArray, entry: VaultEntry): String {392            val key = deriveEntryKey(masterKey, entry.id)393            return try { encryptEntry(key, entry) } finally { VaultCrypto.zero(key) }394        }395396        internal fun decryptEntryOrNull(key: ByteArray, envelopeB64: String): VaultEntry? {397            var pt: ByteArray? = null398            return try {399                val bytes = unb64(envelopeB64)400                if (bytes.size < 12 + 16) null else {401                    val nonce = bytes.copyOfRange(0, 12)402                    val ct = bytes.copyOfRange(12, bytes.size)403                    val cipher = Cipher.getInstance("AES/GCM/NoPadding")404                    cipher.init(Cipher.DECRYPT_MODE, SecretKeySpec(key, "AES"), GCMParameterSpec(128, nonce))405                    cipher.updateAAD(ENTRY_AAD)406                    pt = cipher.doFinal(ct)407                    entryJson.decodeFromString(VaultEntry.serializer(), String(pt, Charsets.UTF_8))408                }409            } catch (_: Exception) {410                null411            } finally {412                // M-05: pt holds the serialized entry including password until the413                // decoded VaultEntry above is the only remaining reference. Zero it414                // so the raw bytes don't outlive the structure they were parsed into.415                pt?.let(VaultCrypto::zero)416            }417        }418419        const val ENTRY_KEY_INFO_SUFFIX = "sync-entry-v1"420        val ENTRY_AAD = "peach-sync-entry-v1".toByteArray(Charsets.UTF_8)421        val rng = SecureRandom()422        val entryJson = Json { encodeDefaults = false; ignoreUnknownKeys = true }423        fun b64(b: ByteArray): String = Base64.getEncoder().encodeToString(b)424        fun unb64(s: String): ByteArray = Base64.getDecoder().decode(s)425    }426}427428class VaultLockedException : Exception("vault_locked")