Add the SdkClientManager and use a single Client per user for vault (#499)

This commit is contained in:
Brian Yencho
2024-01-05 08:57:49 -06:00
committed by Álison Fernandes
parent 6486a6dc6a
commit 41c35e23dd
12 changed files with 671 additions and 107 deletions

View File

@@ -0,0 +1,21 @@
package com.x8bit.bitwarden.data.platform.manager
import com.bitwarden.sdk.Client
/**
* Manages the creation, caching, and destruction of SDK [Client] instances on a per-user basis.
*/
interface SdkClientManager {
/**
* Returns the cached [Client] instance for the given [userId], otherwise creates and caches
* a new one and returns it.
*/
fun getOrCreateClient(userId: String): Client
/**
* Clears any resources from the [Client] associated with the given [userId] and removes it
* from the internal cache.
*/
fun destroyClient(userId: String)
}

View File

@@ -0,0 +1,25 @@
package com.x8bit.bitwarden.data.platform.manager
import com.bitwarden.sdk.Client
/**
* Primary implementation of [SdkClientManager].
*/
class SdkClientManagerImpl(
private val clientProvider: () -> Client = { Client(null) },
) : SdkClientManager {
private val userIdToClientMap = mutableMapOf<String, Client>()
override fun getOrCreateClient(
userId: String,
): Client =
userIdToClientMap.getOrPut(key = userId) { clientProvider() }
override fun destroyClient(
userId: String,
) {
userIdToClientMap
.remove(key = userId)
?.close()
}
}

View File

@@ -6,6 +6,8 @@ import com.x8bit.bitwarden.data.platform.datasource.network.interceptor.AuthToke
import com.x8bit.bitwarden.data.platform.datasource.network.interceptor.BaseUrlInterceptors
import com.x8bit.bitwarden.data.platform.manager.NetworkConfigManager
import com.x8bit.bitwarden.data.platform.manager.NetworkConfigManagerImpl
import com.x8bit.bitwarden.data.platform.manager.SdkClientManager
import com.x8bit.bitwarden.data.platform.manager.SdkClientManagerImpl
import com.x8bit.bitwarden.data.platform.manager.dispatcher.DispatcherManager
import com.x8bit.bitwarden.data.platform.manager.dispatcher.DispatcherManagerImpl
import com.x8bit.bitwarden.data.platform.repository.EnvironmentRepository
@@ -26,6 +28,10 @@ object PlatformManagerModule {
@Singleton
fun provideBitwardenDispatchers(): DispatcherManager = DispatcherManagerImpl()
@Provides
@Singleton
fun provideSdkClientManager(): SdkClientManager = SdkClientManagerImpl()
@Provides
@Singleton
fun provideNetworkConfigManager(

View File

@@ -67,7 +67,11 @@ class GeneratorRepositoryImpl(
.onStart { mutablePasswordHistoryStateFlow.value = LocalDataState.Loading }
.map { encryptedPasswordHistoryList ->
val passwordHistories = encryptedPasswordHistoryList.map { it.toPasswordHistory() }
vaultSdkSource.decryptPasswordHistoryList(passwordHistories)
vaultSdkSource
.decryptPasswordHistoryList(
userId = userId,
passwordHistoryList = passwordHistories,
)
}
.onEach { encryptedPasswordHistoryListResult ->
mutablePasswordHistoryStateFlow.value = encryptedPasswordHistoryListResult.fold(
@@ -148,7 +152,10 @@ class GeneratorRepositoryImpl(
override suspend fun storePasswordHistory(passwordHistoryView: PasswordHistoryView) {
val userId = authDiskSource.userState?.activeUserId ?: return
val encryptedPasswordHistory = vaultSdkSource
.encryptPasswordHistory(passwordHistoryView)
.encryptPasswordHistory(
userId = userId,
passwordHistory = passwordHistoryView,
)
.getOrNull() ?: return
passwordHistoryDiskSource.insertPasswordHistory(
encryptedPasswordHistory.toPasswordHistoryEntity(userId),

View File

@@ -22,84 +22,171 @@ import com.x8bit.bitwarden.data.vault.datasource.sdk.model.InitializeCryptoResul
interface VaultSdkSource {
/**
* Attempts to initialize cryptography functionality for an individual user for the
* Bitwarden SDK with a given [InitUserCryptoRequest].
* Clears any cryptography-related functionality for the given [userId], effectively locking
* the associated vault.
*/
suspend fun initializeCrypto(request: InitUserCryptoRequest): Result<InitializeCryptoResult>
fun clearCrypto(userId: String)
/**
* Attempts to initialize cryptography functionality for an individual user with the given
* [userId] for the Bitwarden SDK with a given [InitUserCryptoRequest].
*/
suspend fun initializeCrypto(
userId: String,
request: InitUserCryptoRequest,
): Result<InitializeCryptoResult>
/**
* Attempts to initialize cryptography functionality for organization data associated with
* the current user for the Bitwarden SDK with a given [InitOrgCryptoRequest].
* the user with the given [userId] for the Bitwarden SDK with a given [InitOrgCryptoRequest].
*
* This should only be called after a successful call to [initializeCrypto].
* This should only be called after a successful call to [initializeCrypto] for the associated
* user.
*/
suspend fun initializeOrganizationCrypto(
userId: String,
request: InitOrgCryptoRequest,
): Result<InitializeCryptoResult>
/**
* Encrypts a [CipherView] returning a [Cipher] wrapped in a [Result].
* Encrypts a [CipherView] for the user with the given [userId], returning a [Cipher] wrapped
* in a [Result].
*
* This should only be called after a successful call to [initializeCrypto] for the associated
* user.
*/
suspend fun encryptCipher(cipherView: CipherView): Result<Cipher>
suspend fun encryptCipher(
userId: String,
cipherView: CipherView,
): Result<Cipher>
/**
* Decrypts a [Cipher] returning a [CipherView] wrapped in a [Result].
* Decrypts a [Cipher] for the user with the given [userId], returning a [CipherView] wrapped
* in a [Result].
*
* This should only be called after a successful call to [initializeCrypto] for the associated
* user.
*/
suspend fun decryptCipher(cipher: Cipher): Result<CipherView>
suspend fun decryptCipher(
userId: String,
cipher: Cipher,
): Result<CipherView>
/**
* Decrypts a list of [Cipher]s returning a list of [CipherListView] wrapped in a [Result].
* Decrypts a list of [Cipher]s for the user with the given [userId], returning a list of
* [CipherListView] wrapped in a [Result].
*
* This should only be called after a successful call to [initializeCrypto] for the associated
* user.
*/
suspend fun decryptCipherListCollection(cipherList: List<Cipher>): Result<List<CipherListView>>
suspend fun decryptCipherListCollection(
userId: String,
cipherList: List<Cipher>,
): Result<List<CipherListView>>
/**
* Decrypts a list of [Cipher]s returning a list of [CipherView] wrapped in a [Result].
* Decrypts a list of [Cipher]s for the user with the given [userId], returning a list of
* [CipherView] wrapped in a [Result].
*
* This should only be called after a successful call to [initializeCrypto] for the associated
* user.
*/
suspend fun decryptCipherList(cipherList: List<Cipher>): Result<List<CipherView>>
suspend fun decryptCipherList(
userId: String,
cipherList: List<Cipher>,
): Result<List<CipherView>>
/**
* Decrypts a [Collection] returning a [CollectionView] wrapped in a [Result].
* Decrypts a [Collection] for the user with the given [userId], returning a [CollectionView]
* wrapped in a [Result].
*
* This should only be called after a successful call to [initializeCrypto] for the associated
* user.
*/
suspend fun decryptCollection(collection: Collection): Result<CollectionView>
suspend fun decryptCollection(
userId: String,
collection: Collection,
): Result<CollectionView>
/**
* Decrypts a list of [Collection]s returning a list of [CollectionView] wrapped in a [Result].
* Decrypts a list of [Collection]s for the user with the given [userId], returning a list of
* [CollectionView] wrapped in a [Result].
*
* This should only be called after a successful call to [initializeCrypto] for the associated
* user.
*/
suspend fun decryptCollectionList(
userId: String,
collectionList: List<Collection>,
): Result<List<CollectionView>>
/**
* Decrypts a [Send] returning a [SendView] wrapped in a [Result].
* Decrypts a [Send] for the user with the given [userId], returning a [SendView] wrapped in a
* [Result].
*
* This should only be called after a successful call to [initializeCrypto] for the associated
* user.
*/
suspend fun decryptSend(send: Send): Result<SendView>
suspend fun decryptSend(
userId: String,
send: Send,
): Result<SendView>
/**
* Decrypts a list of [Send]s returning a list of [SendView] wrapped in a [Result].
* Decrypts a list of [Send]s for the user with the given [userId], returning a list of
* [SendView] wrapped in a [Result].
*
* This should only be called after a successful call to [initializeCrypto] for the associated
* user.
*/
suspend fun decryptSendList(sendList: List<Send>): Result<List<SendView>>
suspend fun decryptSendList(
userId: String,
sendList: List<Send>,
): Result<List<SendView>>
/**
* Decrypts a [Folder] returning a [FolderView] wrapped in a [Result].
* Decrypts a [Folder] for the user with the given [userId], returning a [FolderView] wrapped
* in a [Result].
*
* This should only be called after a successful call to [initializeCrypto] for the associated
* user.
*/
suspend fun decryptFolder(folder: Folder): Result<FolderView>
suspend fun decryptFolder(
userId: String,
folder: Folder,
): Result<FolderView>
/**
* Decrypts a list of [Folder]s returning a list of [FolderView] wrapped in a [Result].
* Decrypts a list of [Folder]s for the user with the given [userId], returning a list of
* [FolderView] wrapped in a [Result].
*
* This should only be called after a successful call to [initializeCrypto] for the associated
* user.
*/
suspend fun decryptFolderList(folderList: List<Folder>): Result<List<FolderView>>
suspend fun decryptFolderList(
userId: String,
folderList: List<Folder>,
): Result<List<FolderView>>
/**
* Encrypts a given password history item.
* Encrypts a given password history item for the user with the given [userId].
*
* This should only be called after a successful call to [initializeCrypto] for the associated
* user.
*/
suspend fun encryptPasswordHistory(
userId: String,
passwordHistory: PasswordHistoryView,
): Result<PasswordHistory>
/**
* Decrypts a list of password history items.
* Decrypts a list of password history items for the user with the given [userId].
*
* This should only be called after a successful call to [initializeCrypto] for the associated
* user.
*/
suspend fun decryptPasswordHistoryList(
userId: String,
passwordHistoryList: List<PasswordHistory>,
): Result<List<PasswordHistoryView>>
}

View File

@@ -14,9 +14,9 @@ import com.bitwarden.core.PasswordHistoryView
import com.bitwarden.core.Send
import com.bitwarden.core.SendView
import com.bitwarden.sdk.BitwardenException
import com.bitwarden.sdk.ClientCrypto
import com.bitwarden.sdk.ClientPasswordHistory
import com.bitwarden.sdk.Client
import com.bitwarden.sdk.ClientVault
import com.x8bit.bitwarden.data.platform.manager.SdkClientManager
import com.x8bit.bitwarden.data.vault.datasource.sdk.model.InitializeCryptoResult
/**
@@ -25,16 +25,21 @@ import com.x8bit.bitwarden.data.vault.datasource.sdk.model.InitializeCryptoResul
*/
@Suppress("TooManyFunctions")
class VaultSdkSourceImpl(
private val clientVault: ClientVault,
private val clientCrypto: ClientCrypto,
private val clientPasswordHistory: ClientPasswordHistory,
private val sdkClientManager: SdkClientManager,
) : VaultSdkSource {
override fun clearCrypto(userId: String) {
sdkClientManager.destroyClient(userId = userId)
}
override suspend fun initializeCrypto(
userId: String,
request: InitUserCryptoRequest,
): Result<InitializeCryptoResult> =
runCatching {
try {
clientCrypto.initializeUserCrypto(req = request)
getClient(userId = userId)
.crypto()
.initializeUserCrypto(req = request)
InitializeCryptoResult.Success
} catch (exception: BitwardenException) {
// The only truly expected error from the SDK is an incorrect key/password.
@@ -43,11 +48,14 @@ class VaultSdkSourceImpl(
}
override suspend fun initializeOrganizationCrypto(
userId: String,
request: InitOrgCryptoRequest,
): Result<InitializeCryptoResult> =
runCatching {
try {
clientCrypto.initializeOrgCrypto(req = request)
getClient(userId = userId)
.crypto()
.initializeOrgCrypto(req = request)
InitializeCryptoResult.Success
} catch (exception: BitwardenException) {
// The only truly expected error from the SDK is for incorrect keys.
@@ -55,53 +63,140 @@ class VaultSdkSourceImpl(
}
}
override suspend fun encryptCipher(cipherView: CipherView): Result<Cipher> =
runCatching { clientVault.ciphers().encrypt(cipherView) }
override suspend fun encryptCipher(
userId: String,
cipherView: CipherView,
): Result<Cipher> =
runCatching {
getClient(userId = userId)
.vault()
.ciphers()
.encrypt(cipherView)
}
override suspend fun decryptCipher(cipher: Cipher): Result<CipherView> =
runCatching { clientVault.ciphers().decrypt(cipher) }
override suspend fun decryptCipher(
userId: String,
cipher: Cipher,
): Result<CipherView> =
runCatching {
getClient(userId = userId)
.vault()
.ciphers()
.decrypt(cipher)
}
override suspend fun decryptCipherListCollection(
userId: String,
cipherList: List<Cipher>,
): Result<List<CipherListView>> =
runCatching { clientVault.ciphers().decryptList(cipherList) }
override suspend fun decryptCipherList(cipherList: List<Cipher>): Result<List<CipherView>> =
runCatching { cipherList.map { clientVault.ciphers().decrypt(it) } }
override suspend fun decryptCollection(collection: Collection): Result<CollectionView> =
runCatching {
clientVault.collections().decrypt(collection)
getClient(userId = userId)
.vault().ciphers()
.decryptList(cipherList)
}
override suspend fun decryptCipherList(
userId: String,
cipherList: List<Cipher>,
): Result<List<CipherView>> =
runCatching {
cipherList.map {
getClient(userId = userId)
.vault()
.ciphers()
.decrypt(it)
}
}
override suspend fun decryptCollection(
userId: String,
collection: Collection,
): Result<CollectionView> =
runCatching {
getClient(userId = userId)
.vault()
.collections()
.decrypt(collection)
}
override suspend fun decryptCollectionList(
userId: String,
collectionList: List<Collection>,
): Result<List<CollectionView>> =
runCatching {
clientVault.collections().decryptList(collectionList)
getClient(userId = userId)
.vault()
.collections()
.decryptList(collectionList)
}
override suspend fun decryptSend(send: Send): Result<SendView> =
runCatching { clientVault.sends().decrypt(send) }
override suspend fun decryptSend(
userId: String,
send: Send,
): Result<SendView> =
runCatching {
getClient(userId = userId)
.vault()
.sends()
.decrypt(send)
}
override suspend fun decryptSendList(sendList: List<Send>): Result<List<SendView>> =
runCatching { sendList.map { clientVault.sends().decrypt(it) } }
override suspend fun decryptSendList(
userId: String,
sendList: List<Send>,
): Result<List<SendView>> =
runCatching {
sendList.map {
getClient(userId = userId)
.vault()
.sends()
.decrypt(it)
}
}
override suspend fun decryptFolder(folder: Folder): Result<FolderView> =
runCatching { clientVault.folders().decrypt(folder) }
override suspend fun decryptFolder(
userId: String,
folder: Folder,
): Result<FolderView> =
runCatching {
getClient(userId = userId)
.vault()
.folders()
.decrypt(folder)
}
override suspend fun decryptFolderList(folderList: List<Folder>): Result<List<FolderView>> =
runCatching { clientVault.folders().decryptList(folderList) }
override suspend fun decryptFolderList(
userId: String,
folderList: List<Folder>,
): Result<List<FolderView>> =
runCatching {
getClient(userId = userId)
.vault()
.folders()
.decryptList(folderList)
}
override suspend fun encryptPasswordHistory(
userId: String,
passwordHistory: PasswordHistoryView,
): Result<PasswordHistory> = runCatching {
clientPasswordHistory.encrypt(passwordHistory)
getClient(userId = userId)
.vault()
.passwordHistory()
.encrypt(passwordHistory)
}
override suspend fun decryptPasswordHistoryList(
userId: String,
passwordHistoryList: List<PasswordHistory>,
): Result<List<PasswordHistoryView>> = runCatching {
clientPasswordHistory.decryptList(passwordHistoryList)
getClient(userId = userId)
.vault()
.passwordHistory()
.decryptList(passwordHistoryList)
}
private fun getClient(
userId: String,
): Client = sdkClientManager.getOrCreateClient(userId = userId)
}

View File

@@ -1,6 +1,6 @@
package com.x8bit.bitwarden.data.vault.datasource.sdk.di
import com.bitwarden.sdk.Client
import com.x8bit.bitwarden.data.platform.manager.SdkClientManager
import com.x8bit.bitwarden.data.vault.datasource.sdk.VaultSdkSource
import com.x8bit.bitwarden.data.vault.datasource.sdk.VaultSdkSourceImpl
import dagger.Module
@@ -19,11 +19,9 @@ object VaultSdkModule {
@Provides
@Singleton
fun providesVaultSdkSource(
client: Client,
sdkClientManager: SdkClientManager,
): VaultSdkSource =
VaultSdkSourceImpl(
clientVault = client.vault(),
clientCrypto = client.crypto(),
clientPasswordHistory = client.vault().passwordHistory(),
sdkClientManager = sdkClientManager,
)
}

View File

@@ -320,6 +320,7 @@ class VaultRepositoryImpl(
emit(
vaultSdkSource
.initializeCrypto(
userId = userId,
request = InitUserCryptoRequest(
kdfParams = kdf,
email = email,
@@ -336,6 +337,7 @@ class VaultRepositoryImpl(
result is InitializeCryptoResult.Success
) {
vaultSdkSource.initializeOrganizationCrypto(
userId = userId,
request = InitOrgCryptoRequest(
organizationKeys = organizationKeys,
),
@@ -363,7 +365,10 @@ class VaultRepositoryImpl(
override suspend fun createCipher(cipherView: CipherView): CreateCipherResult =
vaultSdkSource
.encryptCipher(cipherView = cipherView)
.encryptCipher(
userId = requireNotNull(activeUserId),
cipherView = cipherView,
)
.flatMap { cipher ->
ciphersService
.createCipher(
@@ -385,7 +390,10 @@ class VaultRepositoryImpl(
cipherView: CipherView,
): UpdateCipherResult =
vaultSdkSource
.encryptCipher(cipherView = cipherView)
.encryptCipher(
userId = requireNotNull(activeUserId),
cipherView = cipherView,
)
.flatMap { cipher ->
ciphersService.updateCipher(
cipherId = cipherId,
@@ -421,6 +429,7 @@ class VaultRepositoryImpl(
// TODO: This is temporary. Eventually this needs to be based on the presence of various
// user keys but this will likely require SDK updates to support this (BIT-1190).
private fun setVaultToLocked(userId: String) {
vaultSdkSource.clearCrypto(userId = userId)
mutableVaultStateStateFlow.update {
it.copy(
unlockedVaultUserIds = it.unlockedVaultUserIds - userId,
@@ -473,6 +482,7 @@ class VaultRepositoryImpl(
// the return type here.
vaultSdkSource
.initializeOrganizationCrypto(
userId = syncResponse.profile.id,
request = InitOrgCryptoRequest(
organizationKeys = organizationKeys,
),
@@ -484,10 +494,15 @@ class VaultRepositoryImpl(
): Flow<DataState<List<CipherView>>> =
vaultDiskSource
.getCiphers(userId = userId)
.onStart { mutableCiphersStateFlow.value = DataState.Loading }
.onStart {
mutableCiphersStateFlow.value = DataState.Loading
}
.map {
vaultSdkSource
.decryptCipherList(cipherList = it.toEncryptedSdkCipherList())
.decryptCipherList(
userId = userId,
cipherList = it.toEncryptedSdkCipherList(),
)
.fold(
onSuccess = { ciphers -> DataState.Loaded(ciphers) },
onFailure = { throwable -> DataState.Error(throwable) },
@@ -503,7 +518,10 @@ class VaultRepositoryImpl(
.onStart { mutableFoldersStateFlow.value = DataState.Loading }
.map {
vaultSdkSource
.decryptFolderList(folderList = it.toEncryptedSdkFolderList())
.decryptFolderList(
userId = userId,
folderList = it.toEncryptedSdkFolderList(),
)
.fold(
onSuccess = { folders -> DataState.Loaded(folders) },
onFailure = { throwable -> DataState.Error(throwable) },
@@ -519,7 +537,10 @@ class VaultRepositoryImpl(
.onStart { mutableCollectionsStateFlow.value = DataState.Loading }
.map {
vaultSdkSource
.decryptCollectionList(collectionList = it.toEncryptedSdkCollectionList())
.decryptCollectionList(
userId = userId,
collectionList = it.toEncryptedSdkCollectionList(),
)
.fold(
onSuccess = { collections -> DataState.Loaded(collections) },
onFailure = { throwable -> DataState.Error(throwable) },
@@ -535,7 +556,10 @@ class VaultRepositoryImpl(
.onStart { mutableSendDataStateFlow.value = DataState.Loading }
.map {
vaultSdkSource
.decryptSendList(sendList = it.toEncryptedSdkSendList())
.decryptSendList(
userId = userId,
sendList = it.toEncryptedSdkSendList(),
)
.fold(
onSuccess = { sends -> DataState.Loaded(SendData(sends)) },
onFailure = { throwable -> DataState.Error(throwable) },