Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,7 @@ dependencies {
implementation(libs.androidx.work.runtime.ktx)
implementation(libs.bitwarden.sdk)
implementation(libs.bumptech.glide)
ksp(libs.bumptech.glide.compiler)
implementation(libs.google.hilt.android)
ksp(libs.google.hilt.compiler)
implementation(libs.kotlinx.collections.immutable)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
package com.x8bit.bitwarden.ui.platform.glide

import android.content.Context
import com.bitwarden.network.ssl.createMtlsOkHttpClient
import com.bumptech.glide.Glide
import com.bumptech.glide.Priority
import com.bumptech.glide.Registry
import com.bumptech.glide.annotation.GlideModule
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.HttpException
import com.bumptech.glide.load.Options
import com.bumptech.glide.load.data.DataFetcher
import com.bumptech.glide.load.model.GlideUrl
import com.bumptech.glide.load.model.ModelLoader
import com.bumptech.glide.load.model.ModelLoaderFactory
import com.bumptech.glide.load.model.MultiModelLoaderFactory
import com.bumptech.glide.module.AppGlideModule
import com.x8bit.bitwarden.data.platform.manager.CertificateManager
import dagger.hilt.EntryPoint
import dagger.hilt.InstallIn
import dagger.hilt.android.EntryPointAccessors
import dagger.hilt.components.SingletonComponent
import okhttp3.Call
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.IOException
import java.io.InputStream

/**
* Custom Glide module for the Bitwarden app that configures Glide to use an OkHttpClient
* with mTLS (mutual TLS) support.
*
* This ensures that all icon/image loading requests through Glide present the client certificate
* for mutual TLS authentication, allowing them to pass through Cloudflare's mTLS checks.
*
* The configuration mirrors the SSL setup used in RetrofitsImpl for API calls.
*/
@GlideModule
class BitwardenAppGlideModule : AppGlideModule() {

/**
* Entry point to access Hilt-provided dependencies from non-Hilt managed classes.
*/
@EntryPoint
@InstallIn(SingletonComponent::class)
interface BitwardenGlideEntryPoint {
/**
* Provides access to [CertificateManager] for mTLS certificate management.
*/
fun certificateManager(): CertificateManager
}

override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
// Get CertificateManager from Hilt
val entryPoint = EntryPointAccessors.fromApplication(
context.applicationContext,
BitwardenGlideEntryPoint::class.java,
)
val certificateManager = entryPoint.certificateManager()

val okHttpClient = certificateManager.createMtlsOkHttpClient()

// Register custom ModelLoader that uses our mTLS OkHttpClient
registry.replace(
GlideUrl::class.java,
InputStream::class.java,
OkHttpModelLoaderFactory(okHttpClient),
)
}

/**
* Custom ModelLoaderFactory for Glide 5.x that uses our mTLS-configured OkHttpClient.
*/
private class OkHttpModelLoaderFactory(
private val client: OkHttpClient,
) : ModelLoaderFactory<GlideUrl, InputStream> {

override fun build(
multiFactory: MultiModelLoaderFactory,
): ModelLoader<GlideUrl, InputStream> = OkHttpModelLoader(client)

override fun teardown() {
// No-op
}
}

/**
* Custom ModelLoader that uses OkHttpClient to load images.
*/
private class OkHttpModelLoader(
private val client: OkHttpClient,
) : ModelLoader<GlideUrl, InputStream> {

override fun buildLoadData(
model: GlideUrl,
width: Int,
height: Int,
options: Options,
): ModelLoader.LoadData<InputStream> {
return ModelLoader.LoadData(model, OkHttpDataFetcher(client, model))
}

override fun handles(model: GlideUrl): Boolean = true
}

/**
* DataFetcher that uses OkHttpClient to execute HTTP requests.
*/
private class OkHttpDataFetcher(
private val client: OkHttpClient,
private val url: GlideUrl,
) : DataFetcher<InputStream> {

private var call: Call? = null

override fun loadData(
priority: Priority,
callback: DataFetcher.DataCallback<in InputStream>,
) {
val request = Request.Builder()
.url(url.toStringUrl())
.build()

call = client.newCall(request)

val localCall = client.newCall(request).also { call = it }

val response = try {
localCall.execute()
} catch (e: IOException) {
callback.onLoadFailed(e)
return
}

if (response.isSuccessful) {
callback.onDataReady(response.body.byteStream())
} else {
callback.onLoadFailed(HttpException(response.message, response.code))
}
}

override fun cleanup() {
// Response body cleanup is handled by Glide
}

override fun cancel() {
call?.cancel()
}

override fun getDataClass(): Class<InputStream> = InputStream::class.java

override fun getDataSource(): DataSource = DataSource.REMOTE
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package com.x8bit.bitwarden.ui.platform.glide

import org.junit.jupiter.api.Assertions.assertNotNull
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test

/**
* Test class for [BitwardenAppGlideModule] to verify mTLS configuration is properly applied
* to Glide without requiring a real mTLS server.
*
* These tests verify the module's structure and that it can be instantiated.
* Full integration testing requires running the app and checking logcat for
* "BitwardenGlide" logs when images are loaded.
*/
class BitwardenAppGlideModuleTest {

@Test
fun `BitwardenAppGlideModule should be instantiable`() {
// Verify the module can be created
val module = BitwardenAppGlideModule()

assertNotNull(module)
}

@Test
fun `BitwardenAppGlideModule should have EntryPoint interface for Hilt dependency injection`() {
// Verify the Hilt EntryPoint interface exists for accessing CertificateManager
val entryPointInterface = BitwardenAppGlideModule::class.java
.declaredClasses
.firstOrNull { it.simpleName == "BitwardenGlideEntryPoint" }

assertNotNull(entryPointInterface)
}

@Test
fun `BitwardenGlideEntryPoint should declare certificateManager method`() {
// Verify the EntryPoint has the required method to access CertificateManager
val entryPointInterface = BitwardenAppGlideModule::class.java
.declaredClasses
.firstOrNull { it.simpleName == "BitwardenGlideEntryPoint" }

assertNotNull(entryPointInterface, "BitwardenGlideEntryPoint must exist")

val methods = entryPointInterface!!.declaredMethods
val hasCertificateManagerMethod = methods.any { it.name == "certificateManager" }

assertTrue(hasCertificateManagerMethod)
}
}
2 changes: 2 additions & 0 deletions gradle/libs.versions.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ crashlytics = "3.0.6"
detekt = "1.23.8"
firebaseBom = "34.4.0"
glide = "1.0.0-beta01"
glideKsp = "5.0.0-rc01"
googleGuava = "33.5.0-jre"
googleProtoBufJava = "4.33.0"
googleProtoBufPlugin = "0.9.5"
Expand Down Expand Up @@ -98,6 +99,7 @@ androidx-splashscreen = { module = "androidx.core:core-splashscreen", version.re
androidx-work-runtime-ktx = { module = "androidx.work:work-runtime-ktx", version.ref = "androidxWork" }
bitwarden-sdk = { module = "com.bitwarden:sdk-android", version.ref = "bitwardenSdk" }
bumptech-glide = { module = "com.github.bumptech.glide:compose", version.ref = "glide" }
bumptech-glide-compiler = { module = "com.github.bumptech.glide:ksp", version.ref = "glideKsp" }
detekt-detekt-formatting = { module = "io.gitlab.arturbosch.detekt:detekt-formatting", version.ref = "detekt" }
detekt-detekt-rules = { module = "io.gitlab.arturbosch.detekt:detekt-rules-libraries", version.ref = "detekt" }
google-firebase-bom = { module = "com.google.firebase:firebase-bom", version.ref = "firebaseBom" }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import com.bitwarden.network.interceptor.AuthTokenManager
import com.bitwarden.network.interceptor.BaseUrlInterceptor
import com.bitwarden.network.interceptor.BaseUrlInterceptors
import com.bitwarden.network.interceptor.HeadersInterceptor
import com.bitwarden.network.ssl.BitwardenX509ExtendedKeyManager
import com.bitwarden.network.ssl.CertificateProvider
import com.bitwarden.network.ssl.createSslContext
import com.bitwarden.network.util.HEADER_KEY_AUTHORIZATION
import kotlinx.serialization.json.Json
import okhttp3.MediaType.Companion.toMediaType
Expand All @@ -16,8 +16,6 @@ import retrofit2.Retrofit
import retrofit2.converter.kotlinx.serialization.asConverterFactory
import timber.log.Timber
import java.security.KeyStore
import javax.net.ssl.SSLContext
import javax.net.ssl.TrustManager
import javax.net.ssl.TrustManagerFactory
import javax.net.ssl.X509TrustManager

Expand Down Expand Up @@ -149,28 +147,18 @@ internal class RetrofitsImpl(
)
.build()

private fun createSslTrustManagers(): Array<TrustManager> =
TrustManagerFactory
private fun OkHttpClient.Builder.configureSsl(): OkHttpClient.Builder {
val sslContext = certificateProvider.createSslContext()
val trustManagers = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm())
.apply { init(null as KeyStore?) }
.trustManagers

private fun createSslContext(certificateProvider: CertificateProvider): SSLContext = SSLContext
.getInstance("TLS").apply {
init(
arrayOf(
BitwardenX509ExtendedKeyManager(certificateProvider = certificateProvider),
),
createSslTrustManagers(),
null,
)
}

private fun OkHttpClient.Builder.configureSsl(): OkHttpClient.Builder =
sslSocketFactory(
createSslContext(certificateProvider = certificateProvider).socketFactory,
createSslTrustManagers().first() as X509TrustManager,
return sslSocketFactory(
sslContext.socketFactory,
trustManagers.first() as X509TrustManager,
)
}

//endregion Helper properties and functions
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package com.bitwarden.network.ssl

import okhttp3.OkHttpClient
import java.security.KeyStore
import javax.net.ssl.SSLContext
import javax.net.ssl.TrustManager
import javax.net.ssl.TrustManagerFactory
import javax.net.ssl.X509TrustManager

/**
* Creates an [SSLContext] configured with mTLS support using this [CertificateProvider].
*
* The returned SSLContext will present the client certificate from this provider during
* TLS handshakes, enabling mutual TLS authentication.
*/
fun CertificateProvider.createSslContext(): SSLContext =
SSLContext.getInstance("TLS").apply {
init(
arrayOf(
BitwardenX509ExtendedKeyManager(certificateProvider = this@createSslContext),
),
createSslTrustManagers(),
null,
)
}

/**
* Creates an [OkHttpClient] configured with mTLS support using this [CertificateProvider].
*
* The returned client will present the client certificate from this provider during TLS
* handshakes, allowing requests to pass through mTLS checks.
*/
fun CertificateProvider.createMtlsOkHttpClient(): OkHttpClient {
val sslContext = createSslContext()
val trustManagers = createSslTrustManagers()

return OkHttpClient.Builder()
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

๐Ÿ‘

.sslSocketFactory(
sslContext.socketFactory,
trustManagers.first() as X509TrustManager,
)
.build()
}

/**
* Creates default [TrustManager]s for verifying server certificates.
*
* Uses the system's default trust anchors (trusted CA certificates).
*/
private fun createSslTrustManagers(): Array<TrustManager> =
TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm())
.apply { init(null as KeyStore?) }
.trustManagers
Loading