diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index 40db1d05..3c54f6ad 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -232,6 +232,8 @@ dependencies { testImplementation(libs.mockk) testImplementation(libs.kotlinx.coroutines.test) testImplementation(libs.okhttp.mockwebserver) + // HeldCertificate: a test-only CA, so the server probe can be driven over real TLS. + testImplementation(libs.okhttp.tls) // kxml2 — provides an org.xmlpull.v1 impl on the JVM unit-test // classpath. Android's stock XmlPullParserFactory resolves to the // android.jar Stub on JVM tests; kxml2 is picked up via service- diff --git a/android/app/src/main/java/com/fabledsword/minstrel/auth/ServerProbe.kt b/android/app/src/main/java/com/fabledsword/minstrel/auth/ServerProbe.kt new file mode 100644 index 00000000..57d4d881 --- /dev/null +++ b/android/app/src/main/java/com/fabledsword/minstrel/auth/ServerProbe.kt @@ -0,0 +1,180 @@ +package com.fabledsword.minstrel.auth + +import com.fabledsword.minstrel.api.CleartextToPublicHostException +import com.fabledsword.minstrel.api.MinstrelServerRequest +import kotlinx.coroutines.suspendCancellableCoroutine +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.booleanOrNull +import okhttp3.Call +import okhttp3.Callback +import okhttp3.HttpUrl.Companion.toHttpUrlOrNull +import okhttp3.OkHttpClient +import okhttp3.Request +import okhttp3.Response +import java.io.IOException +import java.net.UnknownHostException +import java.security.GeneralSecurityException +import java.util.concurrent.TimeUnit +import javax.inject.Inject +import javax.net.ssl.SSLPeerUnverifiedException +import kotlin.coroutines.resume +import kotlin.coroutines.resumeWithException + +/** + * Finds the Minstrel server behind an address the user typed. + * + * With no scheme typed it tries `https://` first. It falls back to `http://` + * only when https could not connect at all (refused, timed out, or no TLS on + * that port). A certificate that fails to verify stops the probe instead: + * falling back then would let anyone on the network path force a quiet + * downgrade. A scheme the user typed is used as typed, and still probed, so a + * wrong address fails here rather than at sign-in. + * + * Plain http still passes through [com.fabledsword.minstrel.api.CleartextGuardInterceptor] + * on [client], so the fallback can only succeed on a home-network address. + */ +class ServerProbe internal constructor(client: OkHttpClient, callTimeoutMillis: Long) { + + // Each attempt is short: a probe that stalls holds the sign-in screen. + @Inject constructor(client: OkHttpClient) : this(client, CALL_TIMEOUT_MILLIS) + + private val client: OkHttpClient = client.newBuilder() + .connectTimeout(callTimeoutMillis, TimeUnit.MILLISECONDS) + .callTimeout(callTimeoutMillis, TimeUnit.MILLISECONDS) + .build() + + sealed interface Result { + /** Minstrel answered at [baseUrl], which includes its scheme. */ + data class Found(val baseUrl: String) : Result + + data class Failed(val message: String) : Result + } + + suspend fun find(input: String): Result { + val address = input.trim().trimEnd('/') + val lower = address.lowercase() + return when { + address.isEmpty() -> Result.Failed("Enter your server's address.") + lower.startsWith("https://") || lower.startsWith("http://") -> probeTyped(address) + "://" in address -> Result.Failed("Only https:// and http:// addresses are supported.") + else -> probeBare(address) + } + } + + private suspend fun probeTyped(baseUrl: String): Result = + when (val outcome = attempt(baseUrl)) { + Outcome.Minstrel -> Result.Found(baseUrl) + is Outcome.Stop -> Result.Failed(outcome.message) + is Outcome.Unreachable -> + if (outcome.publicCleartext) { + Result.Failed( + "Plain http:// is only allowed to a server on your home network. " + + "Use https:// for this address.", + ) + } else { + Result.Failed("Couldn't reach $baseUrl.") + } + } + + private suspend fun probeBare(address: String): Result { + val https = "https://$address" + return when (val secure = attempt(https)) { + Outcome.Minstrel -> Result.Found(https) + is Outcome.Stop -> Result.Failed(secure.message) + is Outcome.Unreachable -> { + val http = "http://$address" + when (val plain = attempt(http)) { + Outcome.Minstrel -> Result.Found(http) + is Outcome.Stop -> Result.Failed(plain.message) + // A public host over plain http: say only that https + // failed, so the message never points the user at http. + is Outcome.Unreachable -> Result.Failed("Couldn't reach $https.") + } + } + } + } + + private sealed interface Outcome { + data object Minstrel : Outcome + + /** Nothing answered: the next scheme may be tried. */ + data class Unreachable(val publicCleartext: Boolean = false) : Outcome + + /** Something answered, or TLS failed to verify: stop here. */ + data class Stop(val message: String) : Outcome + } + + private suspend fun attempt(baseUrl: String): Outcome { + val url = "$baseUrl$SETUP_STATUS_PATH".toHttpUrlOrNull() + ?: return Outcome.Stop("That doesn't look like a server address.") + val request = Request.Builder() + .url(url) + // Lets CleartextGuardInterceptor treat the probe as a Minstrel + // server request, as it treats sign-in. + .tag(MinstrelServerRequest::class.java, MinstrelServerRequest) + .build() + return try { + client.newCall(request).await().use { response -> + if (isMinstrel(response)) { + Outcome.Minstrel + } else { + Outcome.Stop("A server answered at $baseUrl, but it isn't Minstrel.") + } + } + } catch (@Suppress("SwallowedException") e: CleartextToPublicHostException) { + Outcome.Unreachable(publicCleartext = true) + } catch (@Suppress("SwallowedException") e: UnknownHostException) { + Outcome.Stop("Couldn't find a server named ${url.host}.") + } catch (e: IOException) { + if (isCertificateFailure(e)) { + Outcome.Stop( + "$baseUrl answered, but its certificate couldn't be verified, " + + "so the app won't connect to it.", + ) + } else { + Outcome.Unreachable() + } + } + } + + // GET /api/auth/setup-status answers {"setup_required": bool} with no + // sign-in, and only Minstrel answers it that way. + private fun isMinstrel(response: Response): Boolean { + val body = if (response.isSuccessful) response.body?.string() else null + val json = body?.let { runCatching { Json.parseToJsonElement(it) }.getOrNull() } as? JsonObject + return (json?.get("setup_required") as? JsonPrimitive)?.booleanOrNull != null + } + + // An unverifiable certificate surfaces as SSLPeerUnverifiedException + // (hostname) or as an SSLHandshakeException caused by a + // CertificateException or CertPathValidatorException (trust). A port + // with no TLS fails the handshake too, but with no such cause. + private fun isCertificateFailure(e: IOException): Boolean = + generateSequence(e) { it.cause } + .take(MAX_CAUSE_DEPTH) + .any { it is SSLPeerUnverifiedException || it is GeneralSecurityException } + + private suspend fun Call.await(): Response = + suspendCancellableCoroutine { continuation -> + continuation.invokeOnCancellation { cancel() } + enqueue( + object : Callback { + override fun onResponse(call: Call, response: Response) { + if (continuation.isActive) continuation.resume(response) else response.close() + } + + override fun onFailure(call: Call, e: IOException) { + if (continuation.isActive) continuation.resumeWithException(e) + } + }, + ) + } + + private companion object { + const val SETUP_STATUS_PATH = "/api/auth/setup-status" + const val CALL_TIMEOUT_MILLIS = 8_000L + const val MAX_CAUSE_DEPTH = 8 + } +} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/auth/ui/ServerUrlScreen.kt b/android/app/src/main/java/com/fabledsword/minstrel/auth/ui/ServerUrlScreen.kt index 04d90763..4ae2b60f 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/auth/ui/ServerUrlScreen.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/auth/ui/ServerUrlScreen.kt @@ -5,13 +5,16 @@ import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material3.Button +import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Surface import androidx.compose.material3.Text +import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue @@ -26,9 +29,11 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.viewModelScope import androidx.navigation.NavHostController import com.fabledsword.minstrel.auth.AuthStore +import com.fabledsword.minstrel.auth.ServerProbe import com.fabledsword.minstrel.nav.Login import com.fabledsword.minstrel.nav.ServerUrl import dagger.hilt.android.lifecycle.HiltViewModel +import kotlinx.coroutines.Job import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow @@ -40,7 +45,7 @@ import javax.inject.Inject data class ServerUrlFormState( val url: String = "", - val saving: Boolean = false, + val probing: Boolean = false, val saved: Boolean = false, val errorMessage: String? = null, ) @@ -48,6 +53,7 @@ data class ServerUrlFormState( @HiltViewModel class ServerUrlViewModel @Inject constructor( private val authStore: AuthStore, + private val probe: ServerProbe, ) : ViewModel() { private val internal = MutableStateFlow( @@ -55,8 +61,8 @@ class ServerUrlViewModel @Inject constructor( // the DEFAULT_BASE_URL placeholder (`http://localhost:8080`) is // an internal HTTP-client fallback, not something a user // typed. Leaving the field empty lets the OutlinedTextField's - // placeholder ("https://minstrel.example.com") show through - // so the user can just type without first having to clear. + // placeholder ("minstrel.example.com") show through so the user + // can just type without first having to clear. ServerUrlFormState( url = authStore.baseUrl.value .takeIf { it != AuthStore.DEFAULT_BASE_URL } @@ -65,29 +71,39 @@ class ServerUrlViewModel @Inject constructor( ) val state: StateFlow = internal.asStateFlow() + private var probeJob: Job? = null + fun setUrl(value: String) { internal.update { it.copy(url = value, errorMessage = null) } } + /** + * Looks for Minstrel at the typed address ([ServerProbe]) and saves the + * full URL that answered, scheme included, so every caller of + * [AuthStore.baseUrl] still receives a complete URL. + */ fun submit() { - val raw = internal.value.url.trim().trimEnd('/') - if (raw.isEmpty()) { - internal.update { it.copy(errorMessage = "Enter a server URL.") } - return - } - if (!raw.startsWith("http://") && !raw.startsWith("https://")) { - internal.update { - it.copy(errorMessage = "URL must start with http:// or https://") + if (internal.value.probing) return + val typed = internal.value.url + probeJob = viewModelScope.launch { + internal.update { it.copy(probing = true, errorMessage = null) } + when (val result = probe.find(typed)) { + is ServerProbe.Result.Found -> { + authStore.setBaseUrl(result.baseUrl) + internal.update { it.copy(probing = false, saved = true) } + } + is ServerProbe.Result.Failed -> + internal.update { it.copy(probing = false, errorMessage = result.message) } } - return - } - viewModelScope.launch { - internal.update { it.copy(saving = true, errorMessage = null) } - authStore.setBaseUrl(raw) - internal.update { it.copy(saving = false, saved = true) } } } + fun cancelProbe() { + probeJob?.cancel() + probeJob = null + internal.update { it.copy(probing = false) } + } + fun consumeSaved() { internal.update { it.copy(saved = false) } } @@ -120,6 +136,7 @@ fun ServerUrlScreen( state = state, onUrlChange = viewModel::setUrl, onSubmit = viewModel::submit, + onCancel = viewModel::cancelProbe, ) } } @@ -129,6 +146,7 @@ private fun ServerUrlForm( state: ServerUrlFormState, onUrlChange: (String) -> Unit, onSubmit: () -> Unit, + onCancel: () -> Unit, ) { Column( modifier = Modifier @@ -143,7 +161,7 @@ private fun ServerUrlForm( color = MaterialTheme.colorScheme.onBackground, ) Text( - text = "Enter the URL of your Minstrel server.", + text = "Enter the address of your Minstrel server.", style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -151,10 +169,13 @@ private fun ServerUrlForm( value = state.url, onValueChange = onUrlChange, modifier = Modifier.fillMaxWidth(), - label = { Text("Server URL") }, - placeholder = { Text("https://minstrel.example.com") }, + label = { Text("Server address") }, + placeholder = { Text("minstrel.example.com") }, + supportingText = { + Text("No need for https://. The app tries https first, then http on your home network.") + }, singleLine = true, - enabled = !state.saving, + enabled = !state.probing, keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Uri, imeAction = ImeAction.Done, @@ -170,8 +191,21 @@ private fun ServerUrlForm( } Button( onClick = onSubmit, - enabled = !state.saving && state.url.isNotBlank(), + enabled = !state.probing && state.url.isNotBlank(), modifier = Modifier.fillMaxWidth(), - ) { Text("Continue") } + ) { + if (state.probing) { + CircularProgressIndicator( + modifier = Modifier.size(20.dp), + color = MaterialTheme.colorScheme.onPrimary, + strokeWidth = 2.dp, + ) + } else { + Text("Continue") + } + } + if (state.probing) { + TextButton(onClick = onCancel) { Text("Cancel") } + } } } diff --git a/android/app/src/test/java/com/fabledsword/minstrel/auth/ServerProbeTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/auth/ServerProbeTest.kt new file mode 100644 index 00000000..5911cc2e --- /dev/null +++ b/android/app/src/test/java/com/fabledsword/minstrel/auth/ServerProbeTest.kt @@ -0,0 +1,133 @@ +package com.fabledsword.minstrel.auth + +import com.fabledsword.minstrel.api.CleartextGuardInterceptor +import kotlinx.coroutines.runBlocking +import okhttp3.OkHttpClient +import okhttp3.mockwebserver.Dispatcher +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.MockWebServer +import okhttp3.mockwebserver.RecordedRequest +import okhttp3.tls.HandshakeCertificates +import okhttp3.tls.HeldCertificate +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertIs +import kotlin.test.assertTrue + +/** + * The sign-in screen's address probe: https first, http only when https could + * not connect, and never past a certificate that fails to verify. + */ +class ServerProbeTest { + private val servers = mutableListOf() + + /** The scheme of every request the probe made, in order. */ + private val schemes = mutableListOf() + + private val ca = HeldCertificate.Builder().certificateAuthority(0).build() + private val strangerCa = HeldCertificate.Builder().certificateAuthority(0).build() + private val serverCertificate = HeldCertificate.Builder() + .signedBy(ca) + .addSubjectAlternativeName("localhost") + .build() + + @AfterEach + fun teardown() { + servers.forEach { it.shutdown() } + } + + private fun server(tls: Boolean, body: String = SETUP_STATUS): String { + val server = MockWebServer() + server.dispatcher = object : Dispatcher() { + override fun dispatch(request: RecordedRequest) = MockResponse().setBody(body) + } + if (tls) { + val certificates = HandshakeCertificates.Builder().heldCertificate(serverCertificate).build() + server.useHttps(certificates.sslSocketFactory(), false) + } + server.start() + servers += server + return "localhost:${server.port}" + } + + private fun probe(trusts: HeldCertificate = ca, cleartextAllowed: Boolean = true): ServerProbe { + val certificates = HandshakeCertificates.Builder() + .addTrustedCertificate(trusts.certificate) + .build() + val client = OkHttpClient.Builder() + .sslSocketFactory(certificates.sslSocketFactory(), certificates.trustManager) + .addInterceptor { chain -> + schemes += chain.request().url.scheme + chain.proceed(chain.request()) + } + .addNetworkInterceptor(CleartextGuardInterceptor { cleartextAllowed }) + .build() + // https aimed at a plain-http port can stall until the call times + // out; a short timeout keeps those cases quick. + return ServerProbe(client, callTimeoutMillis = 2_000) + } + + private fun failure(result: ServerProbe.Result): String = + assertIs(result).message + + @Test + fun `an address without a scheme is saved as https when Minstrel answers there`() { + val address = server(tls = true) + val result = runBlocking { probe().find(address) } + assertEquals(ServerProbe.Result.Found("https://$address"), result) + assertEquals(listOf("https"), schemes) + } + + @Test + fun `when https cannot connect, http is tried and saved`() { + val address = server(tls = false) + val result = runBlocking { probe().find("$address/") } + assertEquals(ServerProbe.Result.Found("http://$address"), result) + assertEquals(listOf("https", "http"), schemes) + } + + @Test + fun `a certificate that fails to verify stops the probe before http is tried`() { + val address = server(tls = true) + val message = failure(runBlocking { probe(trusts = strangerCa).find(address) }) + assertTrue("certificate" in message, message) + assertEquals(listOf("https"), schemes, "fell back to http past a bad certificate") + } + + @Test + fun `plain http typed for a public address is refused by the cleartext guard`() { + val address = server(tls = false) + val message = failure(runBlocking { probe(cleartextAllowed = false).find("http://$address") }) + assertTrue("home network" in message, message) + } + + @Test + fun `a public address with no https says https failed and never suggests http`() { + val address = server(tls = false) + val message = failure(runBlocking { probe(cleartextAllowed = false).find(address) }) + assertEquals("Couldn't reach https://$address.", message) + assertFalse("http://" in message, message) + } + + @Test + fun `a server that answers but is not Minstrel is an error, not a fallback`() { + val address = server(tls = true, body = "It works!") + val message = failure(runBlocking { probe().find(address) }) + assertTrue("isn't Minstrel" in message, message) + assertEquals(listOf("https"), schemes) + } + + @Test + fun `a typed scheme is used as typed`() { + val address = server(tls = false) + val result = runBlocking { probe().find("http://$address") } + assertEquals(ServerProbe.Result.Found("http://$address"), result) + assertEquals(listOf("http"), schemes) + } + + private companion object { + const val SETUP_STATUS = """{"setup_required":false}""" + } +} diff --git a/android/gradle/libs.versions.toml b/android/gradle/libs.versions.toml index 1f6a799d..2780adfa 100644 --- a/android/gradle/libs.versions.toml +++ b/android/gradle/libs.versions.toml @@ -64,6 +64,7 @@ okhttp = { module = "com.squareup.okhttp3:okhttp", version.ref = "okhttp" } okhttp-logging = { module = "com.squareup.okhttp3:logging-interceptor", version.ref = "okhttp" } okhttp-sse = { module = "com.squareup.okhttp3:okhttp-sse", version.ref = "okhttp" } okhttp-mockwebserver = { module = "com.squareup.okhttp3:mockwebserver", version.ref = "okhttp" } +okhttp-tls = { module = "com.squareup.okhttp3:okhttp-tls", version.ref = "okhttp" } kotlinx-serialization-json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", version.ref = "kotlinx-serialization" } kotlinx-coroutines-android = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-android", version.ref = "kotlinx-coroutines" } kotlinx-coroutines-test = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "kotlinx-coroutines" }