mirror of
https://github.com/Monkopedia/rouse-context.git
synced 2026-12-02 18:15:31 +00:00
Switch tunnel WebSocket from Ktor CIO to OkHttp for proper mTLS client cert presentation
This commit is contained in:
commit
a3a0c1aec7
13 changed files with 431 additions and 183 deletions
|
|
@ -100,9 +100,8 @@ dependencies {
|
|||
implementation(project(":work"))
|
||||
implementation(libs.workmanager)
|
||||
|
||||
// Ktor (mTLS WebSocket client for tunnel)
|
||||
implementation(libs.ktor.client.cio)
|
||||
implementation(libs.ktor.client.websockets)
|
||||
// OkHttp (mTLS WebSocket client for tunnel — JSSE properly presents client certs)
|
||||
implementation(libs.okhttp)
|
||||
|
||||
implementation(libs.androidx.core.ktx)
|
||||
implementation(libs.androidx.appcompat)
|
||||
|
|
|
|||
|
|
@ -51,8 +51,10 @@ class RouseApplication : Application() {
|
|||
|
||||
private fun scheduleSecurityChecks() {
|
||||
val request = PeriodicWorkRequestBuilder<SecurityCheckWorker>(
|
||||
4, TimeUnit.HOURS,
|
||||
1, TimeUnit.HOURS
|
||||
4,
|
||||
TimeUnit.HOURS,
|
||||
1,
|
||||
TimeUnit.HOURS
|
||||
).build()
|
||||
WorkManager.getInstance(this).enqueueUniquePeriodicWork(
|
||||
"security-check",
|
||||
|
|
|
|||
|
|
@ -1,127 +0,0 @@
|
|||
package com.rousecontext.app.cert
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import io.ktor.client.HttpClient
|
||||
import io.ktor.client.engine.cio.CIO
|
||||
import io.ktor.client.plugins.websocket.WebSockets
|
||||
import io.ktor.network.tls.CertificateAndKey
|
||||
import java.io.File
|
||||
import java.security.KeyFactory
|
||||
import java.security.PrivateKey
|
||||
import java.security.cert.CertificateFactory
|
||||
import java.security.cert.X509Certificate
|
||||
import java.security.spec.PKCS8EncodedKeySpec
|
||||
|
||||
/**
|
||||
* Creates a Ktor [HttpClient] configured with the device's mTLS client certificate
|
||||
* for connecting to the relay WebSocket endpoint.
|
||||
*
|
||||
* The private key lives in the Android Keystore (hardware-backed HSM).
|
||||
* The cert chain is stored as PEM on disk.
|
||||
*/
|
||||
object MtlsHttpClientFactory {
|
||||
|
||||
private const val TAG = "MtlsHttpClientFactory"
|
||||
private const val CERT_PEM_FILE = "rouse_cert.pem"
|
||||
private const val KEY_PEM_FILE = "rouse_key.pem"
|
||||
|
||||
/**
|
||||
* Build an [HttpClient] that presents the device client certificate during TLS handshake.
|
||||
*
|
||||
* Reads the cert from disk and the private key from Android Keystore synchronously.
|
||||
* Safe to call from Koin module initialization (runs on main thread during app startup).
|
||||
*
|
||||
* @param context Android context for accessing filesDir.
|
||||
* @return An [HttpClient] configured for mTLS, or a plain client if no cert is available.
|
||||
*/
|
||||
fun create(context: Context): HttpClient {
|
||||
val certAndKey = loadCertAndKey(context)
|
||||
|
||||
return if (certAndKey != null) {
|
||||
Log.i(TAG, "Creating mTLS-configured HttpClient")
|
||||
HttpClient(CIO) {
|
||||
engine {
|
||||
https {
|
||||
certificates.add(certAndKey)
|
||||
}
|
||||
}
|
||||
install(WebSockets)
|
||||
}
|
||||
} else {
|
||||
Log.w(TAG, "No device cert available, creating plain HttpClient")
|
||||
HttpClient(CIO) {
|
||||
install(WebSockets)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun loadCertAndKey(context: Context): CertificateAndKey? {
|
||||
val certFile = File(context.filesDir, CERT_PEM_FILE)
|
||||
if (!certFile.exists()) {
|
||||
Log.w(TAG, "No certificate file found at ${certFile.absolutePath}")
|
||||
return null
|
||||
}
|
||||
|
||||
val pemChain = certFile.readText()
|
||||
val certs = parsePemCertificates(pemChain)
|
||||
if (certs.isEmpty()) {
|
||||
Log.w(TAG, "Certificate chain is empty")
|
||||
return null
|
||||
}
|
||||
|
||||
val keyFile = File(context.filesDir, KEY_PEM_FILE)
|
||||
if (!keyFile.exists()) {
|
||||
Log.w(TAG, "No private key file found at ${keyFile.absolutePath}")
|
||||
return null
|
||||
}
|
||||
|
||||
val privateKey = parsePemPrivateKey(keyFile.readText())
|
||||
if (privateKey == null) {
|
||||
Log.w(TAG, "Failed to parse private key PEM")
|
||||
return null
|
||||
}
|
||||
|
||||
Log.i(TAG, "Loaded device cert (${certs.size} certs in chain) and private key")
|
||||
return CertificateAndKey(certs.toTypedArray(), privateKey)
|
||||
}
|
||||
|
||||
private fun parsePemPrivateKey(pem: String): PrivateKey? {
|
||||
val base64 = pem
|
||||
.replace("-----BEGIN PRIVATE KEY-----", "")
|
||||
.replace("-----END PRIVATE KEY-----", "")
|
||||
.replace("-----BEGIN RSA PRIVATE KEY-----", "")
|
||||
.replace("-----END RSA PRIVATE KEY-----", "")
|
||||
.replace("-----BEGIN EC PRIVATE KEY-----", "")
|
||||
.replace("-----END EC PRIVATE KEY-----", "")
|
||||
.replace("\\s".toRegex(), "")
|
||||
return try {
|
||||
val der = java.util.Base64.getDecoder().decode(base64)
|
||||
val spec = PKCS8EncodedKeySpec(der)
|
||||
try {
|
||||
KeyFactory.getInstance("EC").generatePrivate(spec)
|
||||
} catch (_: Exception) {
|
||||
KeyFactory.getInstance("RSA").generatePrivate(spec)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Failed to parse private key", e)
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
private fun parsePemCertificates(pem: String): List<X509Certificate> {
|
||||
val factory = CertificateFactory.getInstance("X.509")
|
||||
val certs = mutableListOf<X509Certificate>()
|
||||
val regex = Regex(
|
||||
"-----BEGIN CERTIFICATE-----(.+?)-----END CERTIFICATE-----",
|
||||
RegexOption.DOT_MATCHES_ALL
|
||||
)
|
||||
for (match in regex.findAll(pem)) {
|
||||
val base64 = match.groupValues[1].replace("\\s".toRegex(), "")
|
||||
val der = java.util.Base64.getDecoder().decode(base64)
|
||||
val cert = factory.generateCertificate(der.inputStream()) as X509Certificate
|
||||
certs.add(cert)
|
||||
}
|
||||
return certs
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,217 @@
|
|||
package com.rousecontext.app.cert
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import com.rousecontext.tunnel.WebSocketFactory
|
||||
import com.rousecontext.tunnel.WebSocketHandle
|
||||
import com.rousecontext.tunnel.WebSocketListener
|
||||
import java.io.File
|
||||
import java.security.KeyFactory
|
||||
import java.security.KeyStore
|
||||
import java.security.PrivateKey
|
||||
import java.security.cert.CertificateFactory
|
||||
import java.security.cert.X509Certificate
|
||||
import java.security.spec.PKCS8EncodedKeySpec
|
||||
import javax.net.ssl.KeyManagerFactory
|
||||
import javax.net.ssl.SSLContext
|
||||
import javax.net.ssl.TrustManagerFactory
|
||||
import javax.net.ssl.X509TrustManager
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import okhttp3.Response
|
||||
import okhttp3.WebSocket
|
||||
import okio.ByteString
|
||||
import okio.ByteString.Companion.toByteString
|
||||
|
||||
/**
|
||||
* Creates a [WebSocketFactory] backed by OkHttp, configured with the device's mTLS
|
||||
* client certificate for connecting to the relay WebSocket endpoint.
|
||||
*
|
||||
* OkHttp uses JSSE (Java's TLS stack) which properly presents client certificates
|
||||
* during the TLS handshake, unlike Ktor CIO which silently drops them.
|
||||
*/
|
||||
object MtlsWebSocketFactory {
|
||||
|
||||
private const val TAG = "MtlsWebSocketFactory"
|
||||
private const val CERT_PEM_FILE = "rouse_cert.pem"
|
||||
private const val KEY_PEM_FILE = "rouse_key.pem"
|
||||
|
||||
/**
|
||||
* Build a [WebSocketFactory] that presents the device client certificate during
|
||||
* TLS handshake.
|
||||
*
|
||||
* @param context Android context for accessing filesDir.
|
||||
* @return A [WebSocketFactory] configured for mTLS, or a plain factory if no cert
|
||||
* is available.
|
||||
*/
|
||||
fun create(context: Context): WebSocketFactory {
|
||||
val okHttpClient = buildOkHttpClient(context)
|
||||
return OkHttpWebSocketFactory(okHttpClient)
|
||||
}
|
||||
|
||||
private fun buildOkHttpClient(context: Context): OkHttpClient {
|
||||
val certAndKey = loadCertAndKey(context)
|
||||
|
||||
return if (certAndKey != null) {
|
||||
Log.i(TAG, "Creating mTLS-configured OkHttpClient")
|
||||
val (certs, privateKey) = certAndKey
|
||||
|
||||
val keyStore = KeyStore.getInstance(KeyStore.getDefaultType()).apply {
|
||||
load(null, null)
|
||||
setKeyEntry("client", privateKey, charArrayOf(), certs.toTypedArray())
|
||||
}
|
||||
|
||||
val keyManagerFactory = KeyManagerFactory.getInstance(
|
||||
KeyManagerFactory.getDefaultAlgorithm()
|
||||
).apply {
|
||||
init(keyStore, charArrayOf())
|
||||
}
|
||||
|
||||
val trustManagerFactory = TrustManagerFactory.getInstance(
|
||||
TrustManagerFactory.getDefaultAlgorithm()
|
||||
).apply {
|
||||
init(null as KeyStore?)
|
||||
}
|
||||
|
||||
val trustManager = trustManagerFactory.trustManagers
|
||||
.first { it is X509TrustManager } as X509TrustManager
|
||||
|
||||
val sslContext = SSLContext.getInstance("TLS").apply {
|
||||
init(keyManagerFactory.keyManagers, trustManagerFactory.trustManagers, null)
|
||||
}
|
||||
|
||||
OkHttpClient.Builder()
|
||||
.sslSocketFactory(sslContext.socketFactory, trustManager)
|
||||
.build()
|
||||
} else {
|
||||
Log.w(TAG, "No device cert available, creating plain OkHttpClient")
|
||||
OkHttpClient()
|
||||
}
|
||||
}
|
||||
|
||||
private fun loadCertAndKey(context: Context): Pair<List<X509Certificate>, PrivateKey>? {
|
||||
val certs = loadCertChain(context)
|
||||
val privateKey = loadPrivateKey(context)
|
||||
if (certs == null || privateKey == null) return null
|
||||
Log.i(TAG, "Loaded device cert (${certs.size} certs in chain) and private key")
|
||||
return certs to privateKey
|
||||
}
|
||||
|
||||
private fun loadCertChain(context: Context): List<X509Certificate>? {
|
||||
val certFile = File(context.filesDir, CERT_PEM_FILE)
|
||||
if (!certFile.exists()) {
|
||||
Log.w(TAG, "No certificate file found at ${certFile.absolutePath}")
|
||||
return null
|
||||
}
|
||||
val certs = parsePemCertificates(certFile.readText())
|
||||
if (certs.isEmpty()) {
|
||||
Log.w(TAG, "Certificate chain is empty")
|
||||
return null
|
||||
}
|
||||
return certs
|
||||
}
|
||||
|
||||
private fun loadPrivateKey(context: Context): PrivateKey? {
|
||||
val keyFile = File(context.filesDir, KEY_PEM_FILE)
|
||||
if (!keyFile.exists()) {
|
||||
Log.w(TAG, "No private key file found at ${keyFile.absolutePath}")
|
||||
return null
|
||||
}
|
||||
val key = parsePemPrivateKey(keyFile.readText())
|
||||
if (key == null) {
|
||||
Log.w(TAG, "Failed to parse private key PEM")
|
||||
}
|
||||
return key
|
||||
}
|
||||
|
||||
private fun parsePemPrivateKey(pem: String): PrivateKey? {
|
||||
val base64 = pem
|
||||
.replace("-----BEGIN PRIVATE KEY-----", "")
|
||||
.replace("-----END PRIVATE KEY-----", "")
|
||||
.replace("-----BEGIN RSA PRIVATE KEY-----", "")
|
||||
.replace("-----END RSA PRIVATE KEY-----", "")
|
||||
.replace("-----BEGIN EC PRIVATE KEY-----", "")
|
||||
.replace("-----END EC PRIVATE KEY-----", "")
|
||||
.replace("\\s".toRegex(), "")
|
||||
return try {
|
||||
val der = java.util.Base64.getDecoder().decode(base64)
|
||||
val spec = PKCS8EncodedKeySpec(der)
|
||||
try {
|
||||
KeyFactory.getInstance("EC").generatePrivate(spec)
|
||||
} catch (_: Exception) {
|
||||
KeyFactory.getInstance("RSA").generatePrivate(spec)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Failed to parse private key", e)
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
private fun parsePemCertificates(pem: String): List<X509Certificate> {
|
||||
val factory = CertificateFactory.getInstance("X.509")
|
||||
val certs = mutableListOf<X509Certificate>()
|
||||
val regex = Regex(
|
||||
"-----BEGIN CERTIFICATE-----(.+?)-----END CERTIFICATE-----",
|
||||
RegexOption.DOT_MATCHES_ALL
|
||||
)
|
||||
for (match in regex.findAll(pem)) {
|
||||
val base64 = match.groupValues[1].replace("\\s".toRegex(), "")
|
||||
val der = java.util.Base64.getDecoder().decode(base64)
|
||||
val cert = factory.generateCertificate(der.inputStream()) as X509Certificate
|
||||
certs.add(cert)
|
||||
}
|
||||
return certs
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* [WebSocketFactory] backed by OkHttp.
|
||||
*
|
||||
* OkHttp's WebSocket uses JSSE for TLS, which correctly presents client certificates
|
||||
* configured via [SSLContext]/[javax.net.ssl.KeyManager] during the mTLS handshake.
|
||||
*/
|
||||
internal class OkHttpWebSocketFactory(
|
||||
private val client: OkHttpClient
|
||||
) : WebSocketFactory {
|
||||
|
||||
override fun connect(url: String, listener: WebSocketListener): WebSocketHandle {
|
||||
val request = Request.Builder()
|
||||
.url(url)
|
||||
.build()
|
||||
|
||||
val ws = client.newWebSocket(
|
||||
request,
|
||||
object : okhttp3.WebSocketListener() {
|
||||
override fun onOpen(webSocket: WebSocket, response: Response) {
|
||||
listener.onOpen()
|
||||
}
|
||||
|
||||
override fun onMessage(webSocket: WebSocket, bytes: ByteString) {
|
||||
listener.onBinaryMessage(bytes.toByteArray())
|
||||
}
|
||||
|
||||
override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
|
||||
listener.onClosing(code, reason)
|
||||
webSocket.close(code, reason)
|
||||
}
|
||||
|
||||
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
|
||||
listener.onFailure(t)
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
return OkHttpWebSocketHandle(ws)
|
||||
}
|
||||
}
|
||||
|
||||
private class OkHttpWebSocketHandle(private val ws: WebSocket) : WebSocketHandle {
|
||||
|
||||
override suspend fun sendBinary(data: ByteArray): Boolean {
|
||||
return ws.send(data.toByteString())
|
||||
}
|
||||
|
||||
override suspend fun close(code: Int, reason: String) {
|
||||
ws.close(code, reason)
|
||||
}
|
||||
}
|
||||
|
|
@ -5,7 +5,7 @@ import com.rousecontext.api.McpIntegration
|
|||
import com.rousecontext.api.NotificationSettingsProvider
|
||||
import com.rousecontext.app.BuildConfig
|
||||
import com.rousecontext.app.cert.FileCertificateStore
|
||||
import com.rousecontext.app.cert.MtlsHttpClientFactory
|
||||
import com.rousecontext.app.cert.MtlsWebSocketFactory
|
||||
import com.rousecontext.app.health.RealHealthConnectRepository
|
||||
import com.rousecontext.app.registry.HealthConnectIntegration
|
||||
import com.rousecontext.app.registry.IntegrationProviderRegistry
|
||||
|
|
@ -116,7 +116,7 @@ val appModule = module {
|
|||
single<TunnelClient> {
|
||||
TunnelClientImpl(
|
||||
scope = get(named("appScope")),
|
||||
httpClient = MtlsHttpClientFactory.create(androidContext())
|
||||
webSocketFactory = MtlsWebSocketFactory.create(androidContext())
|
||||
)
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,21 +1,12 @@
|
|||
package com.rousecontext.tunnel
|
||||
|
||||
import io.ktor.client.HttpClient
|
||||
import io.ktor.client.plugins.websocket.WebSockets
|
||||
import io.ktor.client.plugins.websocket.webSocketSession
|
||||
import io.ktor.websocket.Frame
|
||||
import io.ktor.websocket.WebSocketSession
|
||||
import io.ktor.websocket.close
|
||||
import io.ktor.websocket.readBytes
|
||||
import kotlinx.coroutines.CompletableDeferred
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.cancelAndJoin
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||
import kotlinx.coroutines.flow.SharedFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asSharedFlow
|
||||
import kotlinx.coroutines.isActive
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/**
|
||||
|
|
@ -24,12 +15,11 @@ import kotlinx.coroutines.launch
|
|||
*/
|
||||
class TunnelClientImpl(
|
||||
private val scope: CoroutineScope,
|
||||
private val httpClient: HttpClient = defaultHttpClient()
|
||||
private val webSocketFactory: WebSocketFactory
|
||||
) : TunnelClient {
|
||||
private val stateMachine = ConnectionStateMachine()
|
||||
private var muxDemux: MuxDemux? = null
|
||||
private var session: WebSocketSession? = null
|
||||
private var receiveJob: Job? = null
|
||||
private var wsHandle: WebSocketHandle? = null
|
||||
|
||||
private val _errors = MutableSharedFlow<TunnelError>(extraBufferCapacity = 16)
|
||||
|
||||
|
|
@ -41,34 +31,59 @@ class TunnelClientImpl(
|
|||
override suspend fun connect(url: String) {
|
||||
stateMachine.transition(TunnelState.CONNECTING)
|
||||
try {
|
||||
val wsSession = httpClient.webSocketSession(url)
|
||||
val demux = MuxDemux()
|
||||
demux.onOutgoingFrame = { frame ->
|
||||
wsSession.send(Frame.Binary(true, MuxCodec.encode(frame)))
|
||||
}
|
||||
muxDemux = demux
|
||||
session = wsSession
|
||||
val opened = CompletableDeferred<Unit>()
|
||||
|
||||
receiveJob = scope.launch {
|
||||
try {
|
||||
for (frame in wsSession.incoming) {
|
||||
if (frame is Frame.Binary) {
|
||||
val muxFrame = MuxCodec.decode(frame.readBytes())
|
||||
val handle = webSocketFactory.connect(
|
||||
url,
|
||||
object : WebSocketListener {
|
||||
override fun onOpen() {
|
||||
opened.complete(Unit)
|
||||
}
|
||||
|
||||
override fun onBinaryMessage(data: ByteArray) {
|
||||
val muxFrame = MuxCodec.decode(data)
|
||||
scope.launch {
|
||||
demux.handleFrame(muxFrame)
|
||||
}
|
||||
}
|
||||
// WebSocket closed normally
|
||||
handleDisconnect(TunnelError.WebSocketClosed("WebSocket closed by remote"))
|
||||
} catch (e: Exception) {
|
||||
if (isActive) {
|
||||
handleDisconnect(
|
||||
TunnelError.ConnectionFailed("WebSocket error", e)
|
||||
)
|
||||
|
||||
override fun onClosing(code: Int, reason: String) {
|
||||
scope.launch {
|
||||
handleDisconnect(
|
||||
TunnelError.WebSocketClosed(
|
||||
"WebSocket closed by remote: $code $reason"
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onFailure(error: Throwable) {
|
||||
opened.completeExceptionally(error)
|
||||
scope.launch {
|
||||
handleDisconnect(
|
||||
TunnelError.ConnectionFailed("WebSocket error", error)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
// Wait for the WebSocket handshake to complete
|
||||
opened.await()
|
||||
|
||||
demux.onOutgoingFrame = { frame ->
|
||||
handle.sendBinary(MuxCodec.encode(frame))
|
||||
}
|
||||
|
||||
muxDemux = demux
|
||||
wsHandle = handle
|
||||
|
||||
stateMachine.transition(TunnelState.CONNECTED)
|
||||
} catch (e: TunnelError) {
|
||||
stateMachine.transition(TunnelState.DISCONNECTED)
|
||||
_errors.emit(e)
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
stateMachine.transition(TunnelState.DISCONNECTED)
|
||||
val error = TunnelError.ConnectionFailed("Failed to connect: ${e.message}", e)
|
||||
|
|
@ -80,8 +95,7 @@ class TunnelClientImpl(
|
|||
override suspend fun disconnect() {
|
||||
try {
|
||||
muxDemux?.closeAll()
|
||||
session?.close()
|
||||
receiveJob?.cancelAndJoin()
|
||||
wsHandle?.close()
|
||||
} finally {
|
||||
cleanup()
|
||||
if (stateMachine.state.value != TunnelState.DISCONNECTED) {
|
||||
|
|
@ -99,14 +113,7 @@ class TunnelClientImpl(
|
|||
}
|
||||
|
||||
private fun cleanup() {
|
||||
session = null
|
||||
wsHandle = null
|
||||
muxDemux = null
|
||||
receiveJob = null
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun defaultHttpClient(): HttpClient = HttpClient {
|
||||
install(WebSockets)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,67 @@
|
|||
package com.rousecontext.tunnel
|
||||
|
||||
/**
|
||||
* Abstraction over WebSocket client implementations.
|
||||
*
|
||||
* The tunnel module uses this to stay decoupled from any specific WebSocket library.
|
||||
* On Android, the app module provides an OkHttp-backed implementation that properly
|
||||
* supports mTLS via JSSE. For JVM tests, a Ktor-based implementation is used.
|
||||
*/
|
||||
interface WebSocketFactory {
|
||||
|
||||
/**
|
||||
* Open a WebSocket connection to the given URL and deliver events to [listener].
|
||||
*
|
||||
* The returned [WebSocketHandle] can be used to send binary frames or close
|
||||
* the connection.
|
||||
*
|
||||
* Implementations MUST call [WebSocketListener.onOpen] exactly once on success,
|
||||
* or [WebSocketListener.onFailure] exactly once if the connection cannot be
|
||||
* established.
|
||||
*/
|
||||
fun connect(url: String, listener: WebSocketListener): WebSocketHandle
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle for an open WebSocket connection.
|
||||
*/
|
||||
interface WebSocketHandle {
|
||||
|
||||
/**
|
||||
* Send a binary frame. Returns true if enqueued successfully, false if the
|
||||
* connection is closing/closed.
|
||||
*/
|
||||
suspend fun sendBinary(data: ByteArray): Boolean
|
||||
|
||||
/**
|
||||
* Initiate a graceful close.
|
||||
*/
|
||||
suspend fun close(code: Int = 1000, reason: String = "")
|
||||
}
|
||||
|
||||
/**
|
||||
* Callback interface for WebSocket events.
|
||||
*/
|
||||
interface WebSocketListener {
|
||||
|
||||
/** Connection established. */
|
||||
fun onOpen()
|
||||
|
||||
/** Binary message received. */
|
||||
fun onBinaryMessage(data: ByteArray)
|
||||
|
||||
/**
|
||||
* Connection closed (normal or abnormal).
|
||||
*
|
||||
* @param code WebSocket close code
|
||||
* @param reason WebSocket close reason
|
||||
*/
|
||||
fun onClosing(code: Int, reason: String)
|
||||
|
||||
/**
|
||||
* Connection failed or was lost.
|
||||
*
|
||||
* @param error the cause of the failure
|
||||
*/
|
||||
fun onFailure(error: Throwable)
|
||||
}
|
||||
|
|
@ -0,0 +1,75 @@
|
|||
package com.rousecontext.tunnel
|
||||
|
||||
import io.ktor.client.HttpClient
|
||||
import io.ktor.client.plugins.websocket.WebSockets
|
||||
import io.ktor.client.plugins.websocket.webSocketSession
|
||||
import io.ktor.websocket.Frame
|
||||
import io.ktor.websocket.WebSocketSession
|
||||
import io.ktor.websocket.close
|
||||
import io.ktor.websocket.readBytes
|
||||
import kotlinx.coroutines.CompletableDeferred
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/**
|
||||
* [WebSocketFactory] backed by Ktor's [HttpClient].
|
||||
*
|
||||
* Used for JVM tests. NOT suitable for Android mTLS because Ktor CIO engine
|
||||
* does not properly present client certificates during TLS handshake.
|
||||
*/
|
||||
class KtorWebSocketFactory(
|
||||
private val httpClient: HttpClient = HttpClient { install(WebSockets) },
|
||||
private val scope: CoroutineScope = CoroutineScope(Dispatchers.IO)
|
||||
) : WebSocketFactory {
|
||||
|
||||
override fun connect(url: String, listener: WebSocketListener): WebSocketHandle {
|
||||
val handle = KtorWebSocketHandle()
|
||||
|
||||
scope.launch {
|
||||
try {
|
||||
val session = httpClient.webSocketSession(url)
|
||||
handle.bind(session)
|
||||
listener.onOpen()
|
||||
|
||||
for (frame in session.incoming) {
|
||||
if (frame is Frame.Binary) {
|
||||
listener.onBinaryMessage(frame.readBytes())
|
||||
}
|
||||
}
|
||||
// Normal close
|
||||
listener.onClosing(1000, "WebSocket closed")
|
||||
} catch (e: Exception) {
|
||||
if (handle.isBound()) {
|
||||
listener.onClosing(1006, e.message ?: "Connection lost")
|
||||
} else {
|
||||
listener.onFailure(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return handle
|
||||
}
|
||||
}
|
||||
|
||||
private class KtorWebSocketHandle : WebSocketHandle {
|
||||
private val sessionDeferred = CompletableDeferred<WebSocketSession>()
|
||||
|
||||
fun isBound(): Boolean = sessionDeferred.isCompleted
|
||||
|
||||
fun bind(session: WebSocketSession) {
|
||||
sessionDeferred.complete(session)
|
||||
}
|
||||
|
||||
override suspend fun sendBinary(data: ByteArray): Boolean {
|
||||
val session = sessionDeferred.await()
|
||||
session.send(Frame.Binary(true, data))
|
||||
return true
|
||||
}
|
||||
|
||||
override suspend fun close(code: Int, reason: String) {
|
||||
if (sessionDeferred.isCompleted) {
|
||||
sessionDeferred.await().close()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -28,6 +28,7 @@ class MockRelayServer {
|
|||
body = RegisterResponse(
|
||||
subdomain = "test123.rousecontext.com",
|
||||
cert = MOCK_CERT_PEM,
|
||||
privateKey = MOCK_PRIVATE_KEY_PEM,
|
||||
relayHost = "relay.rousecontext.com"
|
||||
)
|
||||
)
|
||||
|
|
@ -110,6 +111,10 @@ MjYwMTAxMDAwMDAwWjARMQ8wDQYDVQQDDAZ0ZXN0MTIzCAwGdGVzdDEyMwIDAQAB
|
|||
MA0GCSqGSIb3DQEBCwUAA0EAhN+z/EvKbL4TiT3FHSGA
|
||||
-----END CERTIFICATE-----"""
|
||||
|
||||
const val MOCK_PRIVATE_KEY_PEM = """-----BEGIN PRIVATE KEY-----
|
||||
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDZBPk0ybdUXTAN
|
||||
-----END PRIVATE KEY-----"""
|
||||
|
||||
const val MOCK_MISMATCHED_CERT_PEM = """-----BEGIN CERTIFICATE-----
|
||||
MIIBkTCB+wIJANkE+TTJt1RdMA0GCSqGSIb3DQEBCwUAMBMxETAPBgNVBAMMCG90
|
||||
aGVyLWNuMB4XDTIwMDEwMTAwMDAwMFoXDTIxMDEwMTAwMDAwMFowEzERMA8GA1UE
|
||||
|
|
|
|||
|
|
@ -45,6 +45,7 @@ class OnboardingFlowTest {
|
|||
body = RegisterResponse(
|
||||
subdomain = "abc123.rousecontext.com",
|
||||
cert = MockRelayServer.MOCK_CERT_PEM,
|
||||
privateKey = MockRelayServer.MOCK_PRIVATE_KEY_PEM,
|
||||
relayHost = "relay.rousecontext.com"
|
||||
)
|
||||
)
|
||||
|
|
|
|||
|
|
@ -41,7 +41,7 @@ class TunnelClientImplTest {
|
|||
server.start(wait = false)
|
||||
|
||||
try {
|
||||
val client = TunnelClientImpl(this)
|
||||
val client = TunnelClientImpl(this, KtorWebSocketFactory())
|
||||
|
||||
assertEquals(TunnelState.DISCONNECTED, client.state.value)
|
||||
|
||||
|
|
@ -90,7 +90,7 @@ class TunnelClientImplTest {
|
|||
server.start(wait = false)
|
||||
|
||||
try {
|
||||
val client = TunnelClientImpl(this)
|
||||
val client = TunnelClientImpl(this, KtorWebSocketFactory())
|
||||
client.connect("ws://localhost:$port/tunnel")
|
||||
|
||||
val sessionReceived = CompletableDeferred<MuxStream>()
|
||||
|
|
@ -149,7 +149,7 @@ class TunnelClientImplTest {
|
|||
server.start(wait = false)
|
||||
|
||||
try {
|
||||
val client = TunnelClientImpl(this)
|
||||
val client = TunnelClientImpl(this, KtorWebSocketFactory())
|
||||
client.connect("ws://localhost:$port/tunnel")
|
||||
|
||||
val sessionReceived = CompletableDeferred<MuxStream>()
|
||||
|
|
@ -205,7 +205,7 @@ class TunnelClientImplTest {
|
|||
server.start(wait = false)
|
||||
|
||||
try {
|
||||
val client = TunnelClientImpl(this)
|
||||
val client = TunnelClientImpl(this, KtorWebSocketFactory())
|
||||
|
||||
val errorReceived = CompletableDeferred<TunnelError>()
|
||||
val errorJob =
|
||||
|
|
@ -246,7 +246,7 @@ class TunnelClientImplTest {
|
|||
|
||||
@Test
|
||||
fun `connection failure emits error on SharedFlow`() = runBlocking {
|
||||
val client = TunnelClientImpl(this)
|
||||
val client = TunnelClientImpl(this, KtorWebSocketFactory())
|
||||
|
||||
val errorReceived = CompletableDeferred<TunnelError>()
|
||||
val errorJob =
|
||||
|
|
|
|||
|
|
@ -42,7 +42,7 @@ class WebSocketMuxTest {
|
|||
server.start(wait = false)
|
||||
|
||||
try {
|
||||
val client = TunnelClientImpl(this)
|
||||
val client = TunnelClientImpl(this, KtorWebSocketFactory())
|
||||
|
||||
client.connect("ws://localhost:$port/tunnel")
|
||||
|
||||
|
|
@ -78,7 +78,7 @@ class WebSocketMuxTest {
|
|||
server.start(wait = false)
|
||||
|
||||
try {
|
||||
val client = TunnelClientImpl(this)
|
||||
val client = TunnelClientImpl(this, KtorWebSocketFactory())
|
||||
client.connect("ws://localhost:$port/tunnel")
|
||||
|
||||
val sessionReceived = CompletableDeferred<MuxStream>()
|
||||
|
|
@ -149,7 +149,7 @@ class WebSocketMuxTest {
|
|||
server.start(wait = false)
|
||||
|
||||
try {
|
||||
val client = TunnelClientImpl(this)
|
||||
val client = TunnelClientImpl(this, KtorWebSocketFactory())
|
||||
client.connect("ws://localhost:$port/tunnel")
|
||||
|
||||
val sessions = mutableListOf<MuxStream>()
|
||||
|
|
|
|||
|
|
@ -31,6 +31,7 @@ koin = "4.0.0"
|
|||
datastore = "1.1.1"
|
||||
turbine = "1.2.0"
|
||||
mockk = "1.13.16"
|
||||
okhttp = "4.12.0"
|
||||
|
||||
[libraries]
|
||||
androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }
|
||||
|
|
@ -105,6 +106,7 @@ datastore-preferences = { group = "androidx.datastore", name = "datastore-prefer
|
|||
# Test - ViewModels
|
||||
turbine = { group = "app.cash.turbine", name = "turbine", version.ref = "turbine" }
|
||||
mockk = { group = "io.mockk", name = "mockk", version.ref = "mockk" }
|
||||
okhttp = { group = "com.squareup.okhttp3", name = "okhttp", version.ref = "okhttp" }
|
||||
|
||||
# Lifecycle ViewModel Compose
|
||||
lifecycle-viewmodel-compose = { group = "androidx.lifecycle", name = "lifecycle-viewmodel-compose", version.ref = "lifecycle" }
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue