Your phone, on your command. Gotcha is world's first fully on-device AI copilot for Android that turns natural language into real device actions — safely.
MCP follows safe redirects; http allowed with warning (#154)
Rishabh Bajpaidc204aafd026
diff --git a/app/src/main/java/com/gotcha/connectors/mcp/McpHttpClient.kt b/app/src/main/java/com/gotcha/connectors/mcp/McpHttpClient.ktindex efb2032..45e8bf1 100644--- a/app/src/main/java/com/gotcha/connectors/mcp/McpHttpClient.kt+++ b/app/src/main/java/com/gotcha/connectors/mcp/McpHttpClient.kt@@ -16,6 +16,7 @@ import kotlinx.serialization.json.buildJsonObjectimport kotlinx.serialization.json.contentOrNullimport kotlinx.serialization.json.longOrNullimport kotlinx.serialization.json.put+import okhttp3.HttpUrl.Companion.toHttpUrlOrNullimport okhttp3.MediaType.Companion.toMediaTypeimport okhttp3.OkHttpClientimport okhttp3.Request@@ -63,6 +64,9 @@ enum class McpFailure {/** It answered, but not with MCP's JSON-RPC. */NOT_MCP,+ /** A redirect the client will not follow itself (another host, a downgrade). */+ REDIRECT,+/** Any other HTTP status. */HTTP,@@ -103,8 +107,12 @@ data class McpEndpoint(val url: String, val headers: Map<String, String> = empty* response whose id matches, skipping the server's own notifications and* requests, so a stream the server keeps open cannot hang the call;* - caps how much of a reply it reads, counted as bytes arrive;- * - never follows a redirect, since the token and headers would go with it- * to a URL [validateMcpServer] never saw, perhaps over plain http.+ * - follows a redirect only when it cannot leak anything: same origin+ * (scheme, host and port), or an http-to-https upgrade on the same host.+ * Anything else — another host, a port change, an https-to-http downgrade —+ * fails as [McpFailure.REDIRECT] naming where it points, so the user can+ * enter that URL themselves instead of sending the token somewhere+ * [validateMcpServer] never saw, perhaps over plain http.** Stdio servers and the older HTTP+SSE transport are out of scope; the latter* is recognised and reported as [McpFailure.OLD_TRANSPORT].@@ -117,7 +125,7 @@ class McpHttpClient(.build()) {- /** Whatever client is passed in, redirects are off: a 3xx fails as [McpFailure.HTTP] instead. */+ /** Whatever client is passed in, redirects are handled above, not by OkHttp. */private val client = client.newBuilder().followRedirects(false).followSslRedirects(false).build()/** One server's session. Requests on it are serialized, which also keeps re-initialising race-free. */@@ -280,25 +288,66 @@ class McpHttpClient(}private fun post(session: Session, out: Outgoing, firstRequest: Boolean): Reply {+ var url = session.endpoint.url+ var lastCode = 0+ repeat(MAX_REDIRECTS + 1) {+ val response = executePost(session, out, url)+ try {+ if (response.isSuccessful) {+ val sessionId = response.header(HEADER_SESSION_ID)+ val message = if (out.id == null) null else readResponse(response, out.id)+ return Reply(message, sessionId)+ }+ lastCode = response.code+ val location = response.header("Location")+ // Only the codes that keep POST semantics are replayed (301,+ // 302, 307, 308). A 300 or 303 answers a GET instead, so those+ // fail here rather than repeat a side-effecting tool call.+ if (response.code in FOLLOW_CODES && location != null) {+ url = redirectTarget(url, location, response.code)+ } else {+ throw httpFailure(session, response, firstRequest, url)+ }+ } finally {+ response.close()+ }+ }+ throw McpException(McpFailure.HTTP, "too many redirects", lastCode)+ }++ /**+ * Where a redirect points, when it is safe to follow: the same origin+ * (scheme, host and port — the token stays where the user put it), or an+ * http-to-https upgrade on the same host. Anything else throws+ * [McpFailure.REDIRECT] carrying the destination, so the caller can ask+ * the user to enter that URL instead. Relative locations resolve against+ * the request URL. Visible for tests.+ */+ internal fun redirectTarget(currentUrl: String, location: String, code: Int): String {+ val base = currentUrl.toHttpUrlOrNull()+ val target = base?.resolve(location)+ if (base == null || target == null) throw McpException(McpFailure.REDIRECT, location, code)+ val sameOrigin = target.scheme == base.scheme && target.host == base.host && target.port == base.port+ val upgrade = base.scheme == "http" && target.scheme == "https" && target.host == base.host+ if (!sameOrigin && !upgrade) throw McpException(McpFailure.REDIRECT, target.toString(), code)+ return target.toString()+ }++ private fun executePost(session: Session, out: Outgoing, url: String): Response {val builder = Request.Builder()- .url(session.endpoint.url)+ .url(url).header("Accept", "application/json, text/event-stream").post(out.body.toString().toRequestBody(jsonMediaType))session.endpoint.headers.forEach { (k, v) -> builder.header(k, v) }session.headers().forEach { (k, v) -> builder.header(k, v) }- return client.newCall(builder.build()).execute().use { r ->- if (!r.isSuccessful) throw httpFailure(session, r, firstRequest)- val sessionId = r.header(HEADER_SESSION_ID)- val message = if (out.id == null) null else readResponse(r, out.id)- Reply(message, sessionId)- }+ return client.newCall(builder.build()).execute()}/** Socket, TLS and timeout errors, and headers OkHttp refuses, as [McpFailure.NETWORK]. */private fun asMcp(e: Exception): McpException =e as? McpException ?: McpException(McpFailure.NETWORK, e.message ?: e.javaClass.simpleName, cause = e)- private fun httpFailure(session: Session, r: Response, firstRequest: Boolean): McpException {+ private fun httpFailure(session: Session, r: Response, firstRequest: Boolean, url: String): McpException {// For a redirect, where it points is the useful part: the user can enter that URL instead.val detail = r.header("Location").takeIf { r.isRedirect }?: runCatching { r.peekBody(ERROR_BODY_CHARS.toLong()).string() }.getOrDefault("").trim()@@ -306,7 +355,7 @@ class McpHttpClient(401, 403 -> McpException(McpFailure.AUTH, detail, r.code)// The old transport answers POSTs on its SSE URL with 404/405 and// streams an `endpoint` event to a GET instead.- 400, 404, 405 -> if (firstRequest && speaksOldTransport(session)) {+ 400, 404, 405 -> if (firstRequest && speaksOldTransport(session, url)) {McpException(McpFailure.OLD_TRANSPORT, detail, r.code)} else if (r.code == 404) {McpException(McpFailure.NOT_FOUND, detail, r.code)@@ -318,8 +367,8 @@ class McpHttpClient(}/** True when a GET opens an event stream: the 2024-11-05 HTTP+SSE transport. Reads only the headers. */- private fun speaksOldTransport(session: Session): Boolean = runCatching {- val builder = Request.Builder().url(session.endpoint.url).header("Accept", "text/event-stream").get()+ private fun speaksOldTransport(session: Session, url: String): Boolean = runCatching {+ val builder = Request.Builder().url(url).header("Accept", "text/event-stream").get()session.endpoint.headers.forEach { (k, v) -> builder.header(k, v) }client.newCall(builder.build()).execute().use { r ->r.isSuccessful && r.header("Content-Type").orEmpty().startsWith("text/event-stream")@@ -440,6 +489,10 @@ class McpHttpClient(const val HEADER_PROTOCOL_VERSION = "MCP-Protocol-Version"private const val MAX_TOOL_PAGES = 20+ private const val MAX_REDIRECTS = 5++ /** Redirect codes replayed as POST; 300/303 answer a GET instead. */+ private val FOLLOW_CODES = setOf(301, 302, 307, 308)private const val MAX_REPLY_BYTES = 4L * 1024 * 1024private const val MAX_OUTPUT_CHARS = 50_000private const val ERROR_BODY_CHARS = 300diff --git a/app/src/main/java/com/gotcha/connectors/mcp/McpServers.kt b/app/src/main/java/com/gotcha/connectors/mcp/McpServers.ktindex 835f77e..c87c88e 100644--- a/app/src/main/java/com/gotcha/connectors/mcp/McpServers.kt+++ b/app/src/main/java/com/gotcha/connectors/mcp/McpServers.kt@@ -38,24 +38,32 @@ data class McpServerConfig(}/** What is wrong with a server's URL or headers before anything is sent. */-enum class McpConfigProblem { BAD_URL, CLEARTEXT_WITH_SECRET, BAD_HEADER, BAD_TOKEN }+enum class McpConfigProblem { BAD_URL, BAD_HEADER, BAD_TOKEN }/**- * Checks a server before it is contacted. Plain http is accepted for the local- * network (a Home Assistant box, a dev machine), and anywhere when nothing- * secret would travel with it; a token or header sent over http to the- * internet could be read on the way, so that is refused.+ * Checks a server before it is contacted. Both http and https are accepted;+ * [isCleartextWithSecret] names the case that still earns a warning.*/fun validateMcpServer(url: String, token: String, headers: Map<String, String>): McpConfigProblem? {- val parsed = url.trim().toHttpUrlOrNull() ?: return McpConfigProblem.BAD_URL+ url.trim().toHttpUrlOrNull() ?: return McpConfigProblem.BAD_URLif (headers.keys.any { !isValidHeaderName(it) }) return McpConfigProblem.BAD_HEADER// OkHttp refuses to send anything else, so it is caught here rather than on the wire.if (!isHeaderValue(token) || headers.values.any { !isHeaderValue(it) }) return McpConfigProblem.BAD_TOKEN- val secret = token.isNotBlank() || headers.isNotEmpty()- if (!parsed.isHttps && secret && !isLocalHost(parsed.host)) return McpConfigProblem.CLEARTEXT_WITH_SECRETreturn null}+/**+ * True when a token or header would travel over plain http outside the local+ * network, where it could be read on the way. Allowed, but the card says so+ * (issue #154): plain http is accepted for a Home Assistant box or a dev+ * machine, and the warning covers everywhere else.+ */+fun isCleartextWithSecret(url: String, token: String, headers: Map<String, String>): Boolean {+ val parsed = url.trim().toHttpUrlOrNull() ?: return false+ val secret = token.isNotBlank() || headers.isNotEmpty()+ return !parsed.isHttps && secret && !isLocalHost(parsed.host)+}+private fun isHeaderValue(value: String): Boolean = value.all { it == '\t' || it in ' '..'~' }private fun isValidHeaderName(name: String): Boolean =diff --git a/app/src/main/java/com/gotcha/connectors/mcp/McpServersConnector.kt b/app/src/main/java/com/gotcha/connectors/mcp/McpServersConnector.ktindex 99ad230..ed0815a 100644--- a/app/src/main/java/com/gotcha/connectors/mcp/McpServersConnector.kt+++ b/app/src/main/java/com/gotcha/connectors/mcp/McpServersConnector.kt@@ -155,7 +155,9 @@ class McpServersConnector(register()config}- return true to connectedMessage(saved, probe.tools.size, strings)+ // Plain http outside the local network stays allowed, with the warning+ // attached: both schemes are accepted (issue #154).+ return true to connectedMessage(url, token, headers, saved, probe.tools.size, strings)}fun remove(id: String) {@@ -261,11 +263,23 @@ class McpServersConnector(routes = newRoutes.filterKeys { it in registered }}- private fun connectedMessage(config: McpServerConfig, offered: Int, strings: StringLookup): String {+ internal fun connectedMessage(+ url: String,+ token: String,+ headers: Map<String, String>,+ config: McpServerConfig,+ offered: Int,+ strings: StringLookup+ ): String {val label = config.serverName.ifBlank { hostOf(config.url) }val tools = strings.quantity(R.plurals.mcp_tools_count, config.tools.size, config.tools.size)val capped = if (offered > MAX_TOOLS) " " + strings(R.string.mcp_tools_capped, MAX_TOOLS) else ""- return strings(R.string.mcp_connected, label, tools) + capped+ val warning = if (isCleartextWithSecret(url, token, headers)) {+ " " + strings(R.string.mcp_error_cleartext)+ } else {+ ""+ }+ return strings(R.string.mcp_connected, label, tools) + capped + warning}fun failureMessage(e: McpException, strings: StringLookup): String = when (e.kind) {@@ -273,6 +287,7 @@ class McpServersConnector(McpFailure.NOT_FOUND -> strings(R.string.mcp_error_not_found)McpFailure.OLD_TRANSPORT -> strings(R.string.mcp_error_old_transport)McpFailure.NOT_MCP -> strings(R.string.mcp_error_not_mcp, e.detail.take(DETAIL_CHARS))+ McpFailure.REDIRECT -> strings(R.string.mcp_error_redirect, e.detail.take(DETAIL_CHARS))McpFailure.HTTP -> strings(R.string.mcp_error_http, e.httpCode, e.detail.take(DETAIL_CHARS))McpFailure.RPC -> strings(R.string.mcp_error_rpc, e.detail.take(DETAIL_CHARS))McpFailure.NETWORK -> strings(R.string.mcp_error_network, e.detail.take(DETAIL_CHARS))@@ -293,7 +308,6 @@ class McpServersConnector(fun problemMessage(problem: McpConfigProblem, strings: StringLookup): String = when (problem) {McpConfigProblem.BAD_URL -> strings(R.string.mcp_error_bad_url)- McpConfigProblem.CLEARTEXT_WITH_SECRET -> strings(R.string.mcp_error_cleartext)McpConfigProblem.BAD_HEADER -> strings(R.string.mcp_error_bad_header)McpConfigProblem.BAD_TOKEN -> strings(R.string.mcp_error_bad_token)}diff --git a/app/src/main/java/com/gotcha/ui/McpServersCard.kt b/app/src/main/java/com/gotcha/ui/McpServersCard.ktindex 0777683..4df25d6 100644--- a/app/src/main/java/com/gotcha/ui/McpServersCard.kt+++ b/app/src/main/java/com/gotcha/ui/McpServersCard.kt@@ -41,6 +41,7 @@ import com.gotcha.connectors.mcp.McpProbeimport com.gotcha.connectors.mcp.McpServerConfigimport com.gotcha.connectors.mcp.McpServersConnectorimport com.gotcha.connectors.mcp.formatHeaderLines+import com.gotcha.connectors.mcp.isCleartextWithSecretimport com.gotcha.connectors.mcp.parseHeaderLinesimport com.gotcha.i18n.stringLookupimport kotlinx.coroutines.launch@@ -333,7 +334,11 @@ private fun McpServerForm(R.string.mcp_connected,probe.server.name.ifBlank { McpServersConnector.hostOf(url) },strings.quantity(R.plurals.mcp_tools_count, probe.tools.size, probe.tools.size)- )+ ) + if (isCleartextWithSecret(url, token, parsed)) {+ " " + strings(R.string.mcp_error_cleartext)+ } else {+ ""+ }is McpProbe.Failed -> probe.message}busy = falsediff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xmlindex 07d26b4..7242a1a 100644--- a/app/src/main/res/values/strings.xml+++ b/app/src/main/res/values/strings.xml@@ -1753,6 +1753,7 @@<string name="mcp_error_old_transport">This server uses the older HTTP+SSE transport, which Gotcha doesn\'t support yet. Use the server\'s Streamable HTTP address if it has one.</string><string name="mcp_error_not_mcp">The server answered, but not as an MCP server: %1$s</string><string name="mcp_error_http">The server returned HTTP %1$d: %2$s</string>+ <string name="mcp_error_redirect">The server redirects to %1$s, which Gotcha won\'t follow on its own. Enter that address instead.</string><string name="mcp_error_rpc">The server returned an error: %1$s</string><string name="mcp_error_network">Couldn\'t reach the server: %1$s</string><string name="mcp_error_bad_token">The token and header values can only contain plain ASCII characters.</string>diff --git a/app/src/test/java/com/gotcha/connectors/mcp/McpHttpClientTest.kt b/app/src/test/java/com/gotcha/connectors/mcp/McpHttpClientTest.ktindex 5acadf0..78edea6 100644--- a/app/src/test/java/com/gotcha/connectors/mcp/McpHttpClientTest.kt+++ b/app/src/test/java/com/gotcha/connectors/mcp/McpHttpClientTest.kt@@ -230,7 +230,7 @@ class McpHttpClientTest {}@Test- fun `a redirect is not followed, so the secret header stays put`() = runTest {+ fun `a cross-origin redirect is refused, so the secret header stays put`() = runTest {val elsewhere = MockWebServer().apply { start() }val redirecting = MockWebServer().apply {dispatcher = object : Dispatcher() {@@ -248,7 +248,7 @@ class McpHttpClientTest {McpEndpoint(redirecting.url("/mcp").toString(), mapOf("X-API-Key" to "secret"))).initialize()}- assertEquals(McpFailure.HTTP, e.kind)+ assertEquals(McpFailure.REDIRECT, e.kind)assertEquals(307, e.httpCode)assertEquals(elsewhere.url("/mcp").toString(), e.detail)assertEquals(0, elsewhere.requestCount)@@ -258,6 +258,115 @@ class McpHttpClientTest {}}+ @Test+ fun `a same-origin redirect is followed with the headers intact`() = runTest {+ val redirecting = MockWebServer().apply {+ dispatcher = object : Dispatcher() {+ override fun dispatch(request: RecordedRequest): MockResponse {+ if (request.path == "/mcp") {+ return MockResponse()+ .setResponseCode(307)+ .setHeader("Location", "/mcp/")+ }+ return fake.dispatch(request)+ }+ }+ start()+ }+ try {+ val info = client.session(+ McpEndpoint(redirecting.url("/mcp").toString(), mapOf("X-API-Key" to "secret"))+ ).initialize()+ assertEquals("Docs", info.name)+ // Both hops carried the secret: same origin, so nothing leaked.+ redirecting.takeRequest(5, TimeUnit.SECONDS)+ val followed = redirecting.takeRequest(5, TimeUnit.SECONDS)!!+ assertEquals("/mcp/", followed.path)+ assertEquals("secret", followed.getHeader("X-API-Key"))+ } finally {+ redirecting.shutdown()+ }+ }++ @Test+ fun `a same-origin 303 is not replayed as POST`() = runTest {+ val redirecting = MockWebServer().apply {+ dispatcher = object : Dispatcher() {+ override fun dispatch(request: RecordedRequest) = MockResponse()+ .setResponseCode(303)+ .setHeader("Location", "/mcp/")+ }+ start()+ }+ try {+ val e = failureOf {+ client.session(McpEndpoint(redirecting.url("/mcp").toString())).initialize()+ }+ assertEquals(McpFailure.HTTP, e.kind)+ assertEquals(303, e.httpCode)+ assertEquals(1, redirecting.requestCount)+ } finally {+ redirecting.shutdown()+ }+ }++ @Test+ fun `redirect loops fail instead of spinning`() = runTest {+ val looping = MockWebServer().apply {+ dispatcher = object : Dispatcher() {+ override fun dispatch(request: RecordedRequest) = MockResponse()+ .setResponseCode(307)+ .setHeader("Location", "/mcp")+ }+ start()+ }+ try {+ val e = failureOf {+ client.session(McpEndpoint(looping.url("/mcp").toString())).initialize()+ }+ assertEquals(McpFailure.HTTP, e.kind)+ assertEquals(307, e.httpCode)+ // 1 initial + 5 followed hops, then give up.+ assertEquals(6, looping.requestCount)+ } finally {+ looping.shutdown()+ }+ }++ @Test+ fun `redirect targets are classified without sending anything`() {+ val client = McpHttpClient()+ // Same origin, absolute or relative: follow.+ assertEquals(+ "http://h:1/mcp/",+ client.redirectTarget("http://h:1/mcp", "/mcp/", 307)+ )+ assertEquals(+ "http://h:1/other",+ client.redirectTarget("http://h:1/mcp", "http://h:1/other", 301)+ )+ // An http-to-https upgrade on the same host: follow.+ assertEquals(+ "https://h/mcp",+ client.redirectTarget("http://h/mcp", "https://h/mcp", 307)+ )+ // Another host, another port, or a downgrade: refuse with the destination.+ assertEquals("http://other/mcp", failureTarget("http://h/mcp", "http://other/mcp"))+ assertEquals("http://h:2/mcp", failureTarget("http://h:1/mcp", "http://h:2/mcp"))+ assertEquals("http://h/mcp", failureTarget("https://h/mcp", "http://h/mcp"))+ }++ private fun failureTarget(current: String, location: String): String {+ try {+ McpHttpClient().redirectTarget(current, location, 307)+ } catch (e: McpException) {+ assertEquals(McpFailure.REDIRECT, e.kind)+ return e.detail+ }+ fail("expected a redirect refusal")+ error("unreachable")+ }+@Testfun `an event line that never ends is cut at the cap, not buffered whole`() = runTest {val cap = 4 * 1024 * 1024diff --git a/app/src/test/java/com/gotcha/connectors/mcp/McpServersConnectorTest.kt b/app/src/test/java/com/gotcha/connectors/mcp/McpServersConnectorTest.ktindex 5bafcfc..b1589cf 100644--- a/app/src/test/java/com/gotcha/connectors/mcp/McpServersConnectorTest.kt+++ b/app/src/test/java/com/gotcha/connectors/mcp/McpServersConnectorTest.kt@@ -84,6 +84,24 @@ class McpServersConnectorTest {assertTrue(store.map.containsKey("mcp"))}+ @Test+ fun `connected message carries the cleartext warning when one is due`() {+ val config = McpServerConfig(+ id = "x",+ name = "Remote",+ url = "http://mcp.example.com/mcp"+ )+ assertEquals(+ "Connected to mcp.example.com: 0 tools. Use https for a server outside your local network. " ++ "A token or header sent over http can be read on the way.",+ connector.connectedMessage("http://mcp.example.com/mcp", "t", emptyMap(), config, 0, strings)+ )+ assertEquals(+ "Connected to mcp.example.com: 0 tools.",+ connector.connectedMessage("https://mcp.example.com/mcp", "t", emptyMap(), config, 0, strings)+ )+ }+@Testfun `a server that cannot be reached is not saved, and says why`() = runTest {fake.requiredAuth = "Bearer right"diff --git a/app/src/test/java/com/gotcha/connectors/mcp/McpServersTest.kt b/app/src/test/java/com/gotcha/connectors/mcp/McpServersTest.ktindex 7459e39..7b878ef 100644--- a/app/src/test/java/com/gotcha/connectors/mcp/McpServersTest.kt+++ b/app/src/test/java/com/gotcha/connectors/mcp/McpServersTest.kt@@ -47,19 +47,21 @@ class McpServersTest {}@Test- fun `http is fine locally, or with nothing secret, but not with a token over the internet`() {+ fun `http is fine locally or with nothing secret, and warns otherwise`() {assertNull(validateMcpServer("https://mcp.example.com/mcp", "t", emptyMap()))assertNull(validateMcpServer("http://192.168.1.20:8080/mcp", "t", emptyMap()))assertNull(validateMcpServer("http://homeassistant.local:8123/mcp", "t", emptyMap()))assertNull(validateMcpServer("http://mcp.example.com/mcp", "", emptyMap()))- assertEquals(- McpConfigProblem.CLEARTEXT_WITH_SECRET,- validateMcpServer("http://mcp.example.com/mcp", "t", emptyMap())- )- assertEquals(- McpConfigProblem.CLEARTEXT_WITH_SECRET,- validateMcpServer("http://8.8.8.8/mcp", "", mapOf("X-Api-Key" to "k"))- )+ // Both schemes are accepted now (issue #154): cleartext with a secret+ // validates, but still earns the warning.+ assertNull(validateMcpServer("http://mcp.example.com/mcp", "t", emptyMap()))+ assertNull(validateMcpServer("http://8.8.8.8/mcp", "", mapOf("X-Api-Key" to "k")))+ assertFalse(isCleartextWithSecret("https://mcp.example.com/mcp", "t", emptyMap()))+ assertFalse(isCleartextWithSecret("http://192.168.1.20:8080/mcp", "t", emptyMap()))+ assertFalse(isCleartextWithSecret("http://mcp.example.com/mcp", "", emptyMap()))+ assertTrue(isCleartextWithSecret("http://mcp.example.com/mcp", "t", emptyMap()))+ assertTrue(isCleartextWithSecret("http://8.8.8.8/mcp", "", mapOf("X-Api-Key" to "k")))+ assertFalse(isCleartextWithSecret("not a url", "t", emptyMap()))assertEquals(McpConfigProblem.BAD_URL, validateMcpServer("mcp.example.com", "", emptyMap()))assertEquals(McpConfigProblem.BAD_URL, validateMcpServer("ftp://mcp.example.com", "", emptyMap()))assertEquals(McpConfigProblem.BAD_HEADER, validateMcpServer("https://x.com", "", mapOf("Bad Name" to "v")))