[PM-19870] Migrate ServerConfig and ConfigDiskSource to the data module (#4992)

This commit is contained in:
Patrick Honkonen
2025-04-04 14:33:54 -04:00
committed by GitHub
parent c4f54ee93c
commit dda8237ce5
51 changed files with 88 additions and 388 deletions

View File

@@ -4,6 +4,7 @@ plugins {
alias(libs.plugins.android.library)
alias(libs.plugins.hilt)
alias(libs.plugins.kotlin.android)
alias(libs.plugins.kotlin.serialization)
alias(libs.plugins.ksp)
}
@@ -31,6 +32,10 @@ android {
sourceCompatibility(libs.versions.jvmTarget.get())
targetCompatibility(libs.versions.jvmTarget.get())
}
@Suppress("UnstableApiUsage")
testFixtures {
enable = true
}
}
kotlin {
@@ -40,8 +45,31 @@ kotlin {
}
dependencies {
implementation(project(":core"))
implementation(project(":network"))
implementation(libs.androidx.core.ktx)
implementation(libs.androidx.security.crypto)
implementation(libs.google.hilt.android)
ksp(libs.google.hilt.compiler)
implementation(libs.kotlinx.serialization)
testImplementation(platform(libs.junit.bom))
testRuntimeOnly(libs.junit.platform.launcher)
testImplementation(libs.junit.junit5)
testImplementation(libs.junit.vintage)
testImplementation(libs.kotlinx.coroutines.test)
testImplementation(libs.square.turbine)
testFixturesImplementation(project(":core"))
testFixturesImplementation(libs.kotlinx.coroutines.test)
}
tasks {
withType<Test> {
useJUnitPlatform()
maxHeapSize = "2g"
maxParallelForks = Runtime.getRuntime().availableProcessors()
jvmArgs = jvmArgs.orEmpty() + "-XX:+UseParallelGC"
}
}

View File

@@ -0,0 +1,21 @@
package com.bitwarden.data.datasource.disk
import com.bitwarden.data.datasource.disk.model.ServerConfig
import kotlinx.coroutines.flow.Flow
/**
* Primary access point for server configuration-related disk information.
*/
interface ConfigDiskSource {
/**
* The currently persisted [ServerConfig] (or `null` if not set).
*/
var serverConfig: ServerConfig?
/**
* Emits updates that track [ServerConfig]. This will replay the last known value,
* if any.
*/
val serverConfigFlow: Flow<ServerConfig?>
}

View File

@@ -0,0 +1,36 @@
package com.bitwarden.data.datasource.disk
import android.content.SharedPreferences
import com.bitwarden.core.data.repository.util.bufferedMutableSharedFlow
import com.bitwarden.core.data.util.decodeFromStringOrNull
import com.bitwarden.data.datasource.disk.model.ServerConfig
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.onSubscription
import kotlinx.serialization.json.Json
private const val SERVER_CONFIGURATIONS = "serverConfigurations"
/**
* Primary implementation of [ConfigDiskSource].
*/
class ConfigDiskSourceImpl(
sharedPreferences: SharedPreferences,
private val json: Json,
) : BaseDiskSource(sharedPreferences = sharedPreferences),
ConfigDiskSource {
override var serverConfig: ServerConfig?
get() = getString(key = SERVER_CONFIGURATIONS)?.let { json.decodeFromStringOrNull(it) }
set(value) {
putString(
key = SERVER_CONFIGURATIONS,
value = value?.let { json.encodeToString(it) },
)
mutableServerConfigFlow.tryEmit(value)
}
override val serverConfigFlow: Flow<ServerConfig?>
get() = mutableServerConfigFlow.onSubscription { emit(serverConfig) }
private val mutableServerConfigFlow = bufferedMutableSharedFlow<ServerConfig?>(replay = 1)
}

View File

@@ -0,0 +1,28 @@
package com.bitwarden.data.datasource.disk.model
import com.bitwarden.network.model.ConfigResponseJson
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
/**
* A higher-level wrapper around [ConfigResponseJson] that provides a timestamp
* to check if a sync is necessary
*
* @property lastSync The [Long] of the last sync.
* @property serverData The raw [ConfigResponseJson] that contains specific data of the
* server configuration
*/
@Serializable
data class ServerConfig(
@SerialName("lastSync")
val lastSync: Long,
@SerialName("serverData")
val serverData: ConfigResponseJson,
) {
/**
* Whether the server is an official Bitwarden server or not.
*/
val isOfficialBitwardenServer: Boolean
get() = serverData.server == null
}

View File

@@ -0,0 +1,115 @@
package com.bitwarden.data.datasource.disk
import androidx.core.content.edit
import app.cash.turbine.test
import com.bitwarden.core.di.CoreModule
import com.bitwarden.data.datasource.disk.base.FakeSharedPreferences
import com.bitwarden.data.datasource.disk.model.ServerConfig
import com.bitwarden.network.model.ConfigResponseJson
import com.bitwarden.network.model.ConfigResponseJson.EnvironmentJson
import com.bitwarden.network.model.ConfigResponseJson.ServerJson
import kotlinx.coroutines.test.runTest
import kotlinx.serialization.json.JsonPrimitive
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertNull
import org.junit.jupiter.api.Test
import java.time.Instant
class ConfigDiskSourceTest {
private val json = CoreModule.providesJson()
private val fakeSharedPreferences = FakeSharedPreferences()
private val configDiskSource = ConfigDiskSourceImpl(
sharedPreferences = fakeSharedPreferences,
json = json,
)
@Test
fun `serverConfig should pull from and update SharedPreferences`() {
val serverConfigKey = "bwPreferencesStorage:serverConfigurations"
// Shared preferences and the repository start with the same value.
assertNull(configDiskSource.serverConfig)
assertNull(fakeSharedPreferences.getString(serverConfigKey, null))
// Updating the repository updates shared preferences
configDiskSource.serverConfig = SERVER_CONFIG
assertEquals(
json.parseToJsonElement(
SERVER_CONFIG_JSON,
),
json.parseToJsonElement(
fakeSharedPreferences.getString(serverConfigKey, null)!!,
),
)
// Update SharedPreferences updates the repository
fakeSharedPreferences.edit { putString(serverConfigKey, null) }
assertNull(configDiskSource.serverConfig)
}
@Test
fun `serverConfigFlow should react to changes in serverConfig`() =
runTest {
configDiskSource.serverConfigFlow.test {
// The initial values of the Flow and the property are in sync
assertNull(configDiskSource.serverConfig)
assertNull(awaitItem())
// Updating the repository updates shared preferences
configDiskSource.serverConfig = SERVER_CONFIG
assertEquals(SERVER_CONFIG, awaitItem())
}
}
}
private const val SERVER_CONFIG_JSON = """
{
"lastSync": 1698408000000,
"serverData": {
"version": "2024.7.0",
"gitHash": "25cf6119-dirty",
"server": {
"name": "example",
"url": "https://localhost:8080"
},
"environment": {
"vault": "https://localhost:8080",
"api": "http://localhost:4000",
"identity": "http://localhost:33656",
"notifications": "http://localhost:61840",
"sso": "http://localhost:51822"
},
"featureStates": {
"duo-redirect": true,
"flexible-collections-v-1": false
}
}
}
"""
private val SERVER_CONFIG = ServerConfig(
lastSync = Instant.parse("2023-10-27T12:00:00Z").toEpochMilli(),
serverData = ConfigResponseJson(
type = null,
version = "2024.7.0",
gitHash = "25cf6119-dirty",
server = ServerJson(
name = "example",
url = "https://localhost:8080",
),
environment = EnvironmentJson(
cloudRegion = null,
vaultUrl = "https://localhost:8080",
apiUrl = "http://localhost:4000",
identityUrl = "http://localhost:33656",
notificationsUrl = "http://localhost:61840",
ssoUrl = "http://localhost:51822",
),
featureStates = mapOf(
"duo-redirect" to JsonPrimitive(true),
"flexible-collections-v-1" to JsonPrimitive(false),
),
),
)

View File

@@ -0,0 +1,109 @@
package com.bitwarden.data.datasource.disk.base
import android.content.SharedPreferences
/**
* A faked implementation of [SharedPreferences] that is backed by an internal, memory-based map.
*/
class FakeSharedPreferences : SharedPreferences {
private val sharedPreferences: MutableMap<String, Any?> = mutableMapOf()
private val listeners = mutableSetOf<SharedPreferences.OnSharedPreferenceChangeListener>()
override fun contains(key: String): Boolean =
sharedPreferences.containsKey(key)
override fun edit(): SharedPreferences.Editor = Editor()
override fun getAll(): Map<String, *> = sharedPreferences
override fun getBoolean(key: String, defaultValue: Boolean): Boolean =
getValue(key, defaultValue)
override fun getFloat(key: String, defaultValue: Float): Float =
getValue(key, defaultValue)
override fun getInt(key: String, defaultValue: Int): Int =
getValue(key, defaultValue)
override fun getLong(key: String, defaultValue: Long): Long =
getValue(key, defaultValue)
override fun getString(key: String, defaultValue: String?): String? =
getValue(key, defaultValue)
override fun getStringSet(key: String, defaultValue: Set<String>?): Set<String>? =
getValue(key, defaultValue)
override fun registerOnSharedPreferenceChangeListener(
listener: SharedPreferences.OnSharedPreferenceChangeListener,
) {
listeners += listener
}
override fun unregisterOnSharedPreferenceChangeListener(
listener: SharedPreferences.OnSharedPreferenceChangeListener,
) {
listeners -= listener
}
private inline fun <reified T> getValue(
key: String,
defaultValue: T,
): T = sharedPreferences[key] as? T ?: defaultValue
inner class Editor : SharedPreferences.Editor {
private val pendingSharedPreferences = sharedPreferences.toMutableMap()
override fun apply() {
sharedPreferences.apply {
clear()
putAll(pendingSharedPreferences)
// Notify listeners
listeners.forEach { listener ->
pendingSharedPreferences.keys.forEach { key ->
listener.onSharedPreferenceChanged(this@FakeSharedPreferences, key)
}
}
}
}
override fun clear(): SharedPreferences.Editor =
apply { pendingSharedPreferences.clear() }
override fun commit(): Boolean {
apply()
return true
}
override fun putBoolean(key: String, value: Boolean): SharedPreferences.Editor =
putValue(key, value)
override fun putFloat(key: String, value: Float): SharedPreferences.Editor =
putValue(key, value)
override fun putInt(key: String, value: Int): SharedPreferences.Editor =
putValue(key, value)
override fun putLong(key: String, value: Long): SharedPreferences.Editor =
putValue(key, value)
override fun putString(key: String, value: String?): SharedPreferences.Editor =
putValue(key, value)
override fun putStringSet(key: String, value: Set<String>?): SharedPreferences.Editor =
putValue(key, value)
override fun remove(key: String): SharedPreferences.Editor =
apply { pendingSharedPreferences.remove(key) }
private inline fun <reified T> putValue(
key: String,
value: T,
): SharedPreferences.Editor = apply {
value
?.let { pendingSharedPreferences[key] = it }
?: pendingSharedPreferences.remove(key)
}
}
}

View File

@@ -0,0 +1,28 @@
package com.bitwarden.data.datasource.disk.util
import com.bitwarden.core.data.repository.util.bufferedMutableSharedFlow
import com.bitwarden.data.datasource.disk.ConfigDiskSource
import com.bitwarden.data.datasource.disk.model.ServerConfig
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.onSubscription
/**
* A faked [ConfigDiskSource] that holds data in memory.
*/
class FakeConfigDiskSource : ConfigDiskSource {
private var serverConfigValue: ServerConfig? = null
override var serverConfig: ServerConfig?
get() = serverConfigValue
set(value) {
serverConfigValue = value
mutableServerConfigFlow.tryEmit(value)
}
override val serverConfigFlow: Flow<ServerConfig?>
get() = mutableServerConfigFlow
.onSubscription { emit(serverConfig) }
private val mutableServerConfigFlow =
bufferedMutableSharedFlow<ServerConfig?>(replay = 1)
}