Repository navigation
feat: Backup passkeys with the Block Store API #311
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
bd6d684
feat: Prepare Block Store passkeys backup (WIP)
LouisCAD 85f0eb0
feat: Ensure token refreshes are seamless by sharing http clients wit…
LouisCAD fa819cd
feat: Backup passkeys with the Block Store API
LouisCAD fbd9bf4
fix: Fix wrong directory for source file
LouisCAD c10ccc9
fix: Fix wrong package directive
LouisCAD a91285b
chore: Update submodules
LouisCAD d653d51
chore: Update submodules and multiplatform-authenticator
LouisCAD 617f30c
chore: Remove no longer needed dependency declarations
LouisCAD ad10dec
chore: Remove no longer needed SKIE plugin
LouisCAD b19bc99
chore: Use KSP version from Core
LouisCAD 2fb4836
chore: Remove unneeded plugin declaration
LouisCAD f5b57d7
chore: Add clarifying comment as to why removing tokens is safe
LouisCAD d64283e
chore: Add clarifying comment about refreshToken being removed
LouisCAD 768f435
feat: Update backup rules and add BackupAgent for F-Droid
LouisCAD 9daa937
fix: Make KeyPairReference a data class to fix distinct()
LouisCAD e8f526d
chore: Don't back up anything if we can't store the passkeys in Block…
LouisCAD File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
Submodule Core
updated
12 files
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
37 changes: 37 additions & 0 deletions
37
app/src/fdroid/kotlin/com/infomaniak/auth/backup/AuthenticatorFullBackupAgent.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| /* | ||
| * Infomaniak Authenticator - Android | ||
| * Copyright (C) 2026 Infomaniak Network SA | ||
| * | ||
| * This program is free software: you can redistribute it and/or modify | ||
| * it under the terms of the GNU General Public License as published by | ||
| * the Free Software Foundation, either version 3 of the License, or | ||
| * (at your option) any later version. | ||
| * | ||
| * This program is distributed in the hope that it will be useful, | ||
| * but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
| * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
| * GNU General Public License for more details. | ||
| * | ||
| * You should have received a copy of the GNU General Public License | ||
| * along with this program. If not, see <http://www.gnu.org/licenses/>. | ||
| */ | ||
| package com.infomaniak.auth.backup | ||
|
|
||
| import android.app.backup.FullBackupDataOutput | ||
| import androidx.room.immediateTransaction | ||
| import androidx.room.useWriterConnection | ||
| import com.infomaniak.core.auth.models.user.User | ||
| import com.infomaniak.core.auth.room.UserDatabase | ||
| import com.infomaniak.core.common.backup.FullBackupAgent | ||
| import com.infomaniak.multiplatform_authenticator.core.PasskeysStorageLocation | ||
| import kotlinx.coroutines.runBlocking | ||
|
|
||
| class AuthenticatorFullBackupAgent : FullBackupAgent(RestorationPolicy.AllBackedUpFiles) { | ||
|
|
||
| override fun onFullBackup(data: FullBackupDataOutput) { | ||
| PasskeysStorageLocation.dir.listFiles().orEmpty().forEach { file -> | ||
| fullBackupFile(file, data) | ||
| } | ||
| super.onFullBackup(data) | ||
| } | ||
| } |
22 changes: 22 additions & 0 deletions
22
app/src/fdroid/kotlin/com/infomaniak/auth/backup/BlockStoreBackup.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| /* | ||
| * Infomaniak Authenticator - Android | ||
| * Copyright (C) 2026 Infomaniak Network SA | ||
| * | ||
| * This program is free software: you can redistribute it and/or modify | ||
| * it under the terms of the GNU General Public License as published by | ||
| * the Free Software Foundation, either version 3 of the License, or | ||
| * (at your option) any later version. | ||
| * | ||
| * This program is distributed in the hope that it will be useful, | ||
| * but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
| * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
| * GNU General Public License for more details. | ||
| * | ||
| * You should have received a copy of the GNU General Public License | ||
| * along with this program. If not, see <http://www.gnu.org/licenses/>. | ||
| */ | ||
| package com.infomaniak.auth.backup | ||
|
|
||
| object BlockStoreBackup { | ||
| suspend fun restorePasskeys() = Unit | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
67 changes: 67 additions & 0 deletions
67
app/src/standard/kotlin/com/infomaniak/auth/backup/AuthenticatorFullBackupAgent.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,67 @@ | ||
| /* | ||
| * Infomaniak Authenticator - Android | ||
| * Copyright (C) 2026 Infomaniak Network SA | ||
| * | ||
| * This program is free software: you can redistribute it and/or modify | ||
| * it under the terms of the GNU General Public License as published by | ||
| * the Free Software Foundation, either version 3 of the License, or | ||
| * (at your option) any later version. | ||
| * | ||
| * This program is distributed in the hope that it will be useful, | ||
| * but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
| * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
| * GNU General Public License for more details. | ||
| * | ||
| * You should have received a copy of the GNU General Public License | ||
| * along with this program. If not, see <http://www.gnu.org/licenses/>. | ||
| */ | ||
| package com.infomaniak.auth.backup | ||
|
|
||
| import android.app.backup.FullBackupDataOutput | ||
| import androidx.room.immediateTransaction | ||
| import androidx.room.useWriterConnection | ||
| import com.infomaniak.core.auth.models.user.User | ||
| import com.infomaniak.core.auth.room.UserDatabase | ||
| import com.infomaniak.core.common.backup.FullBackupAgent | ||
| import kotlinx.coroutines.runBlocking | ||
|
|
||
| class AuthenticatorFullBackupAgent : FullBackupAgent(RestorationPolicy.AllBackedUpFiles) { | ||
|
|
||
| override fun onFullBackup(data: FullBackupDataOutput) { | ||
| val blockStoreBackupSucceeded = runBlocking { BlockStoreBackup.backupPasskeys() } | ||
| if (!blockStoreBackupSucceeded) return // Don't backup anything if we can't save the passkeys. | ||
|
|
||
| val db = UserDatabase() | ||
| // We don't want to keep tokens in the db for backup, so we remove them temporarily. | ||
| // Note that the app can perfectly recover from this state if the backup process is aborted, here's why: | ||
| // Authenticated API calls with an empty token will result in a 401 http status code, | ||
| // which will lead to the token being refreshed using the passkey. | ||
| val usersWithTokens = runBlocking { db.getUsersAndRemoveTokens() } | ||
| try { | ||
| super.onFullBackup(data) | ||
| } finally { | ||
| runBlocking { db.putTokensBack(usersWithTokens) } | ||
| } | ||
| } | ||
|
|
||
| private suspend fun UserDatabase.getUsersAndRemoveTokens(): List<User> = useWriterConnection { transactor -> | ||
| transactor.immediateTransaction { | ||
| userDao().allUsers().also { users -> | ||
| users.forEach { user -> | ||
| userDao().update(user = user.copy(apiToken = user.apiToken.copy(accessToken = "", refreshToken = null))) | ||
|
LouisCAD marked this conversation as resolved.
|
||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private suspend fun UserDatabase.putTokensBack(usersWithTokens: List<User>) { | ||
| useWriterConnection { transactor -> | ||
| transactor.immediateTransaction { | ||
| usersWithTokens.forEach { user -> | ||
| // We don't need the refreshToken even if it's there because we're using passkeys instead. | ||
| userDao().updateUserToken(user.id, user.apiToken.accessToken) | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
142 changes: 142 additions & 0 deletions
142
app/src/standard/kotlin/com/infomaniak/auth/backup/BlockStoreBackup.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,142 @@ | ||
| /* | ||
| * Infomaniak Authenticator - Android | ||
| * Copyright (C) 2026 Infomaniak Network SA | ||
| * | ||
| * This program is free software: you can redistribute it and/or modify | ||
| * it under the terms of the GNU General Public License as published by | ||
| * the Free Software Foundation, either version 3 of the License, or | ||
| * (at your option) any later version. | ||
| * | ||
| * This program is distributed in the hope that it will be useful, | ||
| * but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
| * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
| * GNU General Public License for more details. | ||
| * | ||
| * You should have received a copy of the GNU General Public License | ||
| * along with this program. If not, see <http://www.gnu.org/licenses/>. | ||
| */ | ||
| @file:OptIn(ExperimentalSerializationApi::class) | ||
|
|
||
| package com.infomaniak.auth.backup | ||
|
|
||
| import com.google.android.gms.auth.blockstore.Blockstore | ||
| import com.google.android.gms.auth.blockstore.BlockstoreClient | ||
| import com.google.android.gms.auth.blockstore.RetrieveBytesRequest | ||
| import com.google.android.gms.auth.blockstore.StoreBytesData | ||
| import com.infomaniak.core.common.cancellable | ||
| import com.infomaniak.core.sentry.SentryLog | ||
| import com.infomaniak.multiplatform_authenticator.core.PasskeysStorageLocation | ||
| import kotlinx.coroutines.Dispatchers | ||
| import kotlinx.coroutines.invoke | ||
| import kotlinx.coroutines.tasks.await | ||
| import kotlinx.serialization.ExperimentalSerializationApi | ||
| import kotlinx.serialization.decodeFromByteArray | ||
| import kotlinx.serialization.encodeToByteArray | ||
| import kotlinx.serialization.protobuf.ProtoBuf | ||
| import splitties.init.appCtx | ||
| import java.io.File | ||
|
|
||
| object BlockStoreBackup { | ||
| private val blockstoreClient = Blockstore.getClient(appCtx) | ||
| private const val PASSKEYS_KEY = "pk" | ||
| private const val TAG = "BlockStoreBackup" | ||
|
|
||
| suspend fun backupPasskeys(): Boolean { | ||
| val backupContent = dumpPasskeys() | ||
| val alreadyBackedUpContent = readPasskeysBackup() | ||
| val bytes = ProtoBuf.encodeToByteArray(backupContent) | ||
| if (alreadyBackedUpContent != null && bytes contentEquals ProtoBuf.encodeToByteArray(alreadyBackedUpContent)) return true | ||
| return writePasskeysBackup(bytes) | ||
| } | ||
|
|
||
| suspend fun restorePasskeys() { | ||
| val passKeysBackup = readPasskeysBackup() ?: return | ||
| applyPasskeysBackup(passKeysBackup) | ||
| } | ||
|
|
||
| private suspend fun writePasskeysBackup(protobufEncodedBytes: ByteArray): Boolean { | ||
| val keySizeInBytes = PASSKEYS_KEY.toByteArray().size | ||
| val contentSizeInBytes = protobufEncodedBytes.size | ||
| val entireSize = contentSizeInBytes + keySizeInBytes | ||
| if (entireSize > BlockstoreClient.MAX_SIZE) { | ||
| SentryLog.e(TAG, "Too many passkeys to backup") { scope -> | ||
| scope.setExtra("Max size", "${BlockstoreClient.MAX_SIZE}B") | ||
| scope.setExtra("Actual size", "${keySizeInBytes}B + ${contentSizeInBytes}B = ${entireSize}B") | ||
| } | ||
| return false | ||
| } | ||
| val storeRequest = StoreBytesData.Builder() | ||
| .setKey(PASSKEYS_KEY) | ||
| .setShouldBackupToCloud(true) | ||
|
LouisCAD marked this conversation as resolved.
|
||
| .setBytes(protobufEncodedBytes) | ||
| .build() | ||
| return runCatching { | ||
| blockstoreClient.storeBytes(storeRequest).await() | ||
| true | ||
| }.cancellable().getOrElse { throwable -> | ||
| SentryLog.wtf(TAG, "Failed to backup passkeys", throwable) | ||
| false | ||
| } | ||
| } | ||
|
|
||
| private suspend fun dumpPasskeys(): PasskeysBackup = Dispatchers.IO { | ||
| PasskeysBackup( | ||
| entries = keyRefs().map { keyPairRef -> | ||
| PasskeysBackup.PasskeyEntry( | ||
| keyPairRef.userId, | ||
| keyPairRef.keyId, | ||
| private = keyFile(keyPairRef, isPublic = false).readBytes(), | ||
| public = keyFile(keyPairRef, isPublic = true).readBytes(), | ||
| ) | ||
| } | ||
| ) | ||
| } | ||
|
|
||
| private suspend fun readPasskeysBackup(): PasskeysBackup? { | ||
| val retrieveRequest = RetrieveBytesRequest.Builder() | ||
| .setKeys(listOf(PASSKEYS_KEY)) | ||
| .build() | ||
| val bytes = blockstoreClient.retrieveBytes(retrieveRequest).await().blockstoreDataMap[PASSKEYS_KEY]?.bytes | ||
| ?: return null | ||
| return ProtoBuf.decodeFromByteArray(bytes) | ||
|
LouisCAD marked this conversation as resolved.
|
||
| } | ||
|
|
||
| private suspend fun applyPasskeysBackup(backup: PasskeysBackup) { | ||
| Dispatchers.IO { | ||
| backup.entries.forEach { entry -> | ||
| val keyPairRef = KeyPairReference(entry.userId, entry.keyId) | ||
| keyFile(keyPairRef, isPublic = false).writeBytes(entry.private) | ||
| keyFile(keyPairRef, isPublic = true).writeBytes(entry.public) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private suspend fun keyRefs(): List<KeyPairReference> = Dispatchers.IO { | ||
| PasskeysStorageLocation.dir.list().orEmpty() | ||
| }.mapNotNull { fileName -> | ||
| val userIdAndKeyId = fileName | ||
| .substringBefore( | ||
| delimiter = ".key", | ||
| missingDelimiterValue = "" | ||
| ) | ||
| .ifEmpty { return@mapNotNull null } | ||
| .substringBeforeLast('-') | ||
| KeyPairReference( | ||
| userId = userIdAndKeyId.substringBefore('-').toLong(), | ||
| keyId = userIdAndKeyId.substringAfter('-') | ||
| ) | ||
| }.distinct() | ||
|
|
||
| private fun keyFile(reference: KeyPairReference, isPublic: Boolean): File = PasskeysStorageLocation.keyFile( | ||
| userId = reference.userId, | ||
| keyId = reference.keyId, | ||
| isPublic = isPublic, | ||
| ) | ||
|
|
||
| private suspend fun isE2eeAvailable(): Boolean = blockstoreClient.isEndToEndEncryptionAvailable.await() | ||
|
|
||
| private data class KeyPairReference( | ||
| val userId: Long, | ||
| val keyId: String, | ||
| ) | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.