提交 Haven Android 仓库源码 v5.87.79

This commit is contained in:
ali
2026-09-10 13:45:36 +08:00
parent 87b452c4dc
commit 22f4ca5830
2524 changed files with 599455 additions and 1 deletions
@@ -0,0 +1,60 @@
plugins {
alias(libs.plugins.android.library)
alias(libs.plugins.hilt)
alias(libs.plugins.ksp)
}
android {
namespace = "sh.haven.core.tunnel"
compileSdk = 37
defaultConfig {
minSdk = 26
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
testOptions {
unitTests.isReturnDefaultValues = true
}
}
dependencies {
// JSch Proxy interface is the integration seam — tunnels expose themselves
// to SshClient by implementing it. JSch stays an `implementation` dep so it
// doesn't leak through `core/tunnel`'s public surface; consumers see only
// `sh.haven.core.ssh.HavenProxy`.
implementation(libs.jsch)
implementation(project(":core:ssh"))
implementation(project(":core:data"))
// The gomobile wgbridge package (wireguard-go + gVisor netstack) lives
// inside the rclone-transport jar — they share a single libgojni.so to
// avoid runtime-class collisions. See rclone-android/go/wgbridge/.
implementation("sh.haven:rclone-transport:0.1.0")
implementation(libs.coroutines.core)
implementation(libs.coroutines.android)
implementation(libs.hilt.android)
// OkHttp WebSocket client for the Cloudflare Access SSH gateway (#154).
implementation(libs.okhttp)
implementation(project(":core:security"))
ksp(libs.hilt.compiler)
testImplementation(libs.junit)
testImplementation(libs.mockk)
testImplementation(libs.coroutines.test)
testImplementation(libs.okhttp.mockwebserver)
// Android's android.jar stubs out org.json.JSONObject in unit tests
// (returns defaults), so add the real JSON lib for tests that
// exercise TailscaleConfigBlob's JSON envelope. Same package, same
// class — JVM resolves to the real impl when both are on the path.
testImplementation("org.json:json:20260814")
}
kotlin {
compilerOptions {
jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17)
}
}
@@ -0,0 +1,49 @@
package sh.haven.core.tunnel
import com.jcraft.jsch.Proxy
import com.jcraft.jsch.SocketFactory
import java.io.InputStream
import java.io.OutputStream
import java.net.Socket
/**
* JSch [Proxy] adapter that reaches the SSH server through an **authenticated**
* SOCKS5 proxy via [ProxySocketFactory], instead of JSch's own `ProxySOCKS5`.
*
* Why bypass JSch (#227): mwiede/jsch 2.28.0's `ProxySOCKS5` builds the RFC 1929
* username/password sub-negotiation using `String.length()` (the **character**
* count) for the length octets and the `arraycopy` length, while the field
* content is `Util.str2byte(...)` (**UTF-8 bytes**). For any non-ASCII credential
* the two disagree, so a malformed auth packet goes out and the proxy answers
* `server status = 01`. [ProxySocketFactory] derives the length octets from the
* encoded byte arrays, so it is correct for non-ASCII credentials too.
*
* JSch hands us the destination `(host, port)` at connect time;
* [ProxySocketFactory.createSocket] performs the proxy handshake to reach it and
* returns a connected [Socket] whose streams carry the onward SSH traffic.
* Mirrors [TunnelProxy] — same `connect` → stream I/O → `close` lifecycle.
*/
class AuthenticatedProxy(private val factory: ProxySocketFactory) : Proxy {
private var socket: Socket? = null
override fun connect(socketFactory: SocketFactory?, host: String, port: Int, timeout: Int) {
// ProxySocketFactory owns its own connect timeout; JSch's `timeout`
// (default 10 s) is ignored in favour of the factory's 30 s default,
// matching TunnelProxy's "more headroom for proxy setup" stance.
socket = factory.createSocket(host, port)
}
override fun getInputStream(): InputStream =
socket?.getInputStream() ?: error("AuthenticatedProxy.connect() not called")
override fun getOutputStream(): OutputStream =
socket?.getOutputStream() ?: error("AuthenticatedProxy.connect() not called")
override fun getSocket(): Socket? = socket
override fun close() {
try { socket?.close() } catch (_: Throwable) { /* best-effort */ }
socket = null
}
}
@@ -0,0 +1,86 @@
package sh.haven.core.tunnel
import org.json.JSONObject
/**
* Storage envelope for Cloudflare Tunnel configs (with optional Cloudflare
* Access auth on top). Encoded into
* [sh.haven.core.data.db.entities.TunnelConfig.configText] (which is then
* encrypted at rest by the repository).
*
* Each row binds the tunnel to a single Cloudflare Tunnel hostname — the
* server-side connector decides which upstream SSH host to forward to,
* either statically (one route → one target) or via the optional
* [jumpDestination] field which is forwarded as
* `Cf-Access-Jump-Destination` on the WS upgrade.
*
* **JWT is optional**: unprotected Cloudflare Tunnel routes need no auth.
* If the user signs in via the in-app WebView, the resulting JWT and
* its expiry are cached here for re-use.
*
* Format (UTF-8 JSON):
* ```
* {
* "hostname": "ssh.example.com",
* "teamDomain": "myteam.cloudflareaccess.com", // optional, only when Access is in front
* "jwt": "eyJhbGciOi…", // optional, empty when no Access
* "jwtExpiresAt": 1737934800, // 0 if jwt is empty / unparseable
* "jumpDestination": "internal-host:22" // optional, bastion-mode only
* }
* ```
*
* Unknown JSON keys are ignored — adding fields (service-token credentials,
* last-used host) won't break older clients reading newer blobs.
*/
data class CloudflareAccessConfigBlob(
val hostname: String,
val teamDomain: String,
val jwt: String,
val jwtExpiresAt: Long,
val jumpDestination: String = "",
) {
fun encode(): ByteArray {
val json = JSONObject().apply {
put("hostname", hostname)
put("teamDomain", teamDomain)
put("jwt", jwt)
put("jwtExpiresAt", jwtExpiresAt)
if (jumpDestination.isNotBlank()) {
put("jumpDestination", jumpDestination)
}
}
return json.toString().toByteArray(Charsets.UTF_8)
}
fun isJwtExpired(nowEpochSeconds: Long = System.currentTimeMillis() / 1000): Boolean =
jwt.isNotBlank() && jwtExpiresAt in 1 until nowEpochSeconds
companion object {
/**
* Decode bytes from [TunnelConfig.configText]. Throws
* [IllegalArgumentException] on malformed JSON or missing hostname.
* JWT is optional — blobs from rc4+ may legitimately omit it for
* unprotected Cloudflare Tunnel routes.
*/
fun parse(bytes: ByteArray): CloudflareAccessConfigBlob {
val text = String(bytes, Charsets.UTF_8).trim()
val json = try {
JSONObject(text)
} catch (t: Throwable) {
throw IllegalArgumentException("CloudflareAccessConfigBlob: not valid JSON", t)
}
val hostname = json.optString("hostname").trim()
val teamDomain = json.optString("teamDomain").trim()
val jwt = json.optString("jwt").trim()
val jumpDestination = json.optString("jumpDestination").trim()
require(hostname.isNotEmpty()) { "CloudflareAccessConfigBlob: missing hostname" }
return CloudflareAccessConfigBlob(
hostname = hostname,
teamDomain = teamDomain,
jwt = jwt,
jwtExpiresAt = json.optLong("jwtExpiresAt", 0L),
jumpDestination = jumpDestination,
)
}
}
}
@@ -0,0 +1,344 @@
package sh.haven.core.tunnel
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.WebSocket
import okhttp3.WebSocketListener
import okio.ByteString
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.io.PipedInputStream
import java.io.PipedOutputStream
import java.net.InetSocketAddress
import java.util.concurrent.CopyOnWriteArraySet
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicReference
/**
* [Tunnel] implementation that talks to a **Cloudflare Tunnel** published
* hostname — the same wire protocol `cloudflared access ssh --hostname <h>`
* uses on desktop, irrespective of whether the route has Cloudflare Access
* sitting in front of it.
*
* Wire shape (verified against cloudflared's `carrier/websocket.go` and
* `carrier/carrier.go` — Cloudflare don't publish a spec):
* - Dial `wss://<hostname>/` (root path, no subprotocol).
* - Plain binary frames ferry raw TCP bytes both directions; SSH then
* runs unmodified on top.
* - **Optional** `Cf-Access-Token: <jwt>` header carries an Access JWT
* when the route is Access-protected. Sent as an HTTP header — *not*
* a cookie, despite the browser-side flow setting `CF_Authorization`.
* - **Optional** `Cf-Access-Jump-Destination: <host>:<port>` header for
* bastion-mode multi-target tunnels (the server-side connector reads
* it to decide which SSH host to forward to).
*
* If the hostname is Access-protected and no JWT is supplied, Cloudflare's
* edge responds with HTTP 302 to `/cdn-cgi/access/login/...`. We detect
* that in [mapFailure] and surface a "sign in required" hint rather than
* the bare "Expected HTTP 101".
*
* Per-hostname proxy: every [dial] must target the configured [hostname];
* port is ignored because the server-side connector decides the upstream
* SSH target (statically from the published route, or dynamically via
* [jumpDestination] when set).
*
* Lifetime: the [OkHttpClient] is owned by the caller (Hilt singleton)
* and not closed in [close] — only the per-dial WebSockets are torn
* down. Since this backend has no L3 surface there's no [socksAddress]
* implementation; rclone / IronRDP can't route through it.
*
* Thread-safety: [dial] may be called concurrently. Each dial owns its
* own WebSocket; the parent tunnel only tracks them for [close] to
* cancel any still-live streams.
*
* The class is still named `CloudflareAccessTunnel` for compatibility
* with rc1–rc3 code paths; it now handles both unprotected Cloudflare
* Tunnel routes and Access-protected ones uniformly. See GH #154.
*/
class CloudflareAccessTunnel internal constructor(
private val hostname: String,
/** Cloudflare Access JWT. Empty / blank for unprotected Tunnel routes. */
private val jwt: String,
/** Optional `Cf-Access-Jump-Destination` value, e.g. `internal-host:22`. Blank to omit. */
private val jumpDestination: String,
private val httpClient: OkHttpClient,
/** Test seam. Production code passes null; tests point at MockWebServer. */
private val gatewayUrlOverride: String? = null,
) : Tunnel {
companion object {
/**
* Public factory for callers outside `:core:tunnel` (the
* production path goes through [DefaultTunnelFactory] and never
* needs this). Used by the Settings "Test connection" button to
* build a transient tunnel without going through [TunnelManager]
* — the test deliberately isn't ref-counted into any live
* session.
*/
fun forTest(
hostname: String,
jwt: String,
httpClient: OkHttpClient,
jumpDestination: String = "",
): CloudflareAccessTunnel = CloudflareAccessTunnel(
hostname = hostname,
jwt = jwt,
jumpDestination = jumpDestination,
httpClient = httpClient,
)
}
private val live = CopyOnWriteArraySet<WebSocketTunneledConnection>()
override fun dial(host: String, port: Int, timeoutMs: Int): TunneledConnection {
require(host.equals(hostname, ignoreCase = true)) {
"CloudflareAccessTunnel is bound to '$hostname'; cannot dial '$host'"
}
val url = gatewayUrlOverride ?: "https://$hostname/"
val builder = Request.Builder()
.url(url)
.header("User-Agent", "Haven-CF-Tunnel")
if (jwt.isNotBlank()) {
builder.header("Cf-Access-Token", jwt)
}
if (jumpDestination.isNotBlank()) {
builder.header("Cf-Access-Jump-Destination", jumpDestination)
}
val request = builder.build()
// Per-dial client. Two adjustments vs the shared singleton:
// - Apply the requested call timeout (production paths typically
// pass timeoutMs > 0 so reads don't block forever).
// - Disable redirect-following. Cloudflare's signal that a route
// is Access-protected is a 302 to `/cdn-cgi/access/login/...`
// on the team domain; OkHttp's WS dialer would otherwise
// silently chase that redirect to a *different host* and
// return whatever 404 the team domain serves, hiding the
// diagnostic we actually want. cloudflared/gorilla never
// follows WS redirects; we mirror that here.
val client = httpClient.newBuilder()
.followRedirects(false)
.followSslRedirects(false)
.apply {
if (timeoutMs > 0) {
callTimeout(timeoutMs.toLong(), TimeUnit.MILLISECONDS)
}
}
.build()
val conn = WebSocketTunneledConnection(hostname) { live.remove(it) }
live.add(conn)
try {
conn.start(client, request, timeoutMs)
} catch (t: Throwable) {
live.remove(conn)
throw t
}
return conn
}
override fun socksAddress(): InetSocketAddress? = null
override fun close() {
// Snapshot to avoid CME if a dial finishes concurrently.
live.toList().forEach { runCatching { it.close() } }
live.clear()
}
}
/**
* [TunneledConnection] backed by an OkHttp [WebSocket]. Inbound binary
* frames are piped into [inputStream]; [outputStream] writes are sent as
* single binary frames per call. SSH already produces suitably-sized
* writes, so we don't bother batching.
*/
private class WebSocketTunneledConnection(
private val hostname: String,
private val onClose: (WebSocketTunneledConnection) -> Unit,
) : TunneledConnection {
private val pipeBufferSize = 64 * 1024
private val inboundSink = PipedOutputStream()
private val inboundSource = PipedInputStream(inboundSink, pipeBufferSize)
private val openedLatch = CountDownLatch(1)
private val openError = AtomicReference<Throwable?>(null)
private val webSocket = AtomicReference<WebSocket?>(null)
@Volatile private var closed = false
override val inputStream: InputStream = inboundSource
override val outputStream: OutputStream = object : OutputStream() {
override fun write(b: Int) {
write(byteArrayOf((b and 0xFF).toByte()), 0, 1)
}
override fun write(b: ByteArray, off: Int, len: Int) {
if (closed) throw IOException("Cloudflare Tunnel closed")
if (len == 0) return
val ws = webSocket.get() ?: throw IOException("Cloudflare Tunnel WebSocket not yet open")
val slice = if (off == 0 && len == b.size) b else b.copyOfRange(off, off + len)
val ok = ws.send(ByteString.of(*slice))
if (!ok) throw IOException("Cloudflare Tunnel WebSocket send queue closed")
}
}
fun start(client: OkHttpClient, request: Request, timeoutMs: Int) {
val listener = object : WebSocketListener() {
override fun onOpen(ws: WebSocket, response: Response) {
webSocket.set(ws)
openedLatch.countDown()
}
override fun onMessage(ws: WebSocket, bytes: ByteString) {
if (closed) return
try {
bytes.write(inboundSink)
inboundSink.flush()
} catch (t: Throwable) {
// Reader closed before WS finished — common on
// disconnect, not worth re-raising.
}
}
override fun onMessage(ws: WebSocket, text: String) {
// Cloudflare's gateway never sends text frames. If we
// see one, treat it as a protocol error so callers
// don't silently drop bytes.
fail(ws, IOException("Cloudflare Tunnel sent unexpected text frame"))
}
override fun onClosing(ws: WebSocket, code: Int, reason: String) {
closeQuietly()
}
override fun onClosed(ws: WebSocket, code: Int, reason: String) {
closeQuietly()
}
override fun onFailure(ws: WebSocket, t: Throwable, response: Response?) {
fail(ws, mapFailure(t, response))
}
private fun fail(ws: WebSocket, error: Throwable) {
if (openError.compareAndSet(null, error)) {
openedLatch.countDown()
}
closeQuietly()
}
}
client.newWebSocket(request, listener)
val awaitMs = if (timeoutMs > 0) timeoutMs.toLong() else 30_000L
val opened = openedLatch.await(awaitMs, TimeUnit.MILLISECONDS)
openError.get()?.let { throw it }
if (!opened) {
close()
throw IOException("Cloudflare Tunnel WebSocket open timed out after ${awaitMs}ms")
}
}
/**
* Translate OkHttp's failure surface into a connection-log-friendly
* exception.
*
* Detection ladder (most-specific first):
* - **302 to `/cdn-cgi/access/login`** → "this hostname is Access-protected,
* sign in to capture a JWT". Mirrors cloudflared's
* `IsAccessResponse` check.
* - **401/403** → "JWT rejected, re-authenticate". Only meaningful
* if a JWT was sent; otherwise the more useful signal is the
* 302 above.
* - **5xx** → "Cloudflare gateway error".
*
* Every failure also carries the Cloudflare-specific debug headers
* (`cf-ray` for support correlation, `cf-mitigated` for WAF blocks,
* `Server`, `WWW-Authenticate`, `Location`) plus the first 256 chars
* of any HTML body. JWT-shaped values are redacted before logging.
*/
private fun mapFailure(t: Throwable, response: Response?): Throwable {
val code = response?.code
val location = response?.header("Location").orEmpty()
val detail = buildDiagnostics(response)
val base = when {
code == 302 && location.contains(ACCESS_LOGIN_PATH) ->
"Cloudflare Tunnel '$hostname' requires Access auth — sign in to capture a JWT"
code == 401 || code == 403 ->
"Cloudflare Tunnel '$hostname' rejected request (HTTP $code) — JWT may be invalid or expired"
code != null && code in 500..599 ->
"Cloudflare gateway error for '$hostname' (HTTP $code)"
code == null ->
"Cloudflare Tunnel WebSocket to '$hostname' failed: ${t.message}"
else ->
"Cloudflare Tunnel WebSocket to '$hostname' failed: HTTP $code ${t.message ?: ""}".trim()
}
return IOException(if (detail.isEmpty()) base else "$base — $detail", t)
}
/**
* Build a `key=value; key=value` diagnostic string from the upgrade
* response. Empty if [response] is null. Body excerpt is included
* only if the content-type looks textual and the body is small.
*/
private fun buildDiagnostics(response: Response?): String {
if (response == null) return ""
val parts = mutableListOf<String>()
for (name in DIAG_HEADERS) {
response.header(name)?.let { parts += "$name=${redact(it)}" }
}
// Body excerpt — guarded by content-type and length. OkHttp
// peekBody buffers without consuming the upstream source, so
// we don't break any downstream consumer of `response`.
val contentType = response.header("Content-Type").orEmpty()
val textual = contentType.startsWith("text/", ignoreCase = true) ||
contentType.contains("html", ignoreCase = true) ||
contentType.contains("json", ignoreCase = true) ||
contentType.isEmpty()
if (textual) {
runCatching {
val peeked = response.peekBody(BODY_PEEK_BYTES)
val excerpt = peeked.string().take(BODY_EXCERPT_CHARS).replace(Regex("\\s+"), " ").trim()
if (excerpt.isNotEmpty()) parts += "body=\"$excerpt\""
}
}
return parts.joinToString("; ")
}
/** Redact JWT-shaped values so debug strings don't leak credentials. */
private fun redact(value: String): String {
if (value.length > 40 && value.contains('.')) return "<redacted ${value.length} chars>"
return value
}
private companion object {
/** Headers we want in the diagnostic line, in priority order. */
val DIAG_HEADERS = listOf(
"cf-ray",
"cf-mitigated",
"Server",
"WWW-Authenticate",
"Location",
)
const val BODY_PEEK_BYTES = 1024L
const val BODY_EXCERPT_CHARS = 256
/** cloudflared's signal that a route is Access-protected (carrier.go:120). */
const val ACCESS_LOGIN_PATH = "/cdn-cgi/access/login"
}
override fun close() {
if (closed) return
closed = true
webSocket.getAndSet(null)?.let { runCatching { it.close(1000, null) } }
runCatching { inboundSink.close() }
runCatching { inboundSource.close() }
onClose(this)
}
private fun closeQuietly() {
runCatching { inboundSink.close() }
}
}
@@ -0,0 +1,238 @@
package sh.haven.core.tunnel
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.io.InputStream
import java.net.InetSocketAddress
import java.net.Proxy
import java.net.Socket
import javax.net.SocketFactory
/**
* javax.net.SocketFactory that dials through a SOCKS5 / SOCKS4 / HTTP
* proxy (the legacy `proxyType`/`proxyHost`/`proxyPort` columns on
* ConnectionProfile).
*
* Two handshake paths:
*
* - **No proxy auth** ([proxyUser] null): backed by the JDK's built-in
* [Proxy] support — `Socket(java.net.Proxy)` performs the SOCKS or
* HTTP-CONNECT handshake transparently when [Socket.connect] is called.
* Unchanged from before, byte-for-byte.
* - **Proxy auth** ([proxyUser] set, #227): the JDK only sources proxy
* credentials from a global `java.net.Authenticator` / system
* properties, which is racy across concurrent connections. So when
* credentials are present we run the handshake ourselves, per-connection:
* SOCKS5 → RFC 1929 username/password; HTTP → `Proxy-Authorization:
* Basic`. SOCKS4 carries only a userid and the JDK can't pass it without
* a global Authenticator, so SOCKS4-with-creds falls through to the JDK
* path (the SSH/JSch path handles SOCKS4 userid directly via
* `setUserPasswd`; SOCKS4-auth over non-SSH transports is out of scope).
*
* Hostnames are passed unresolved to the proxy so DNS lookups happen on
* the proxy side, not locally — important for Tor (.onion addresses
* have no public DNS) and for any setup where the proxy can resolve
* names the local resolver can't. The manual SOCKS5 path uses the
* domain-name address type (ATYP 0x03) and HTTP CONNECT names the host
* directly, both preserving remote resolution.
*
* Used by [TunnelResolver] when the profile has proxy fields set but no
* `tunnelConfigId` — the SSH path already had this routing for years
* via [TunnelResolver.jschProxy]; this factory brings VNC, SMB, and
* other non-JSch transports to the same place (#149).
*/
class ProxySocketFactory(
private val proxyType: String,
private val proxyHost: String,
private val proxyPort: Int,
private val connectTimeoutMs: Int = 30_000,
private val proxyUser: String? = null,
private val proxyPassword: String? = null,
) : SocketFactory() {
override fun createSocket(host: String, port: Int): Socket {
val type = proxyType.uppercase()
// Manual authenticated handshake only when credentials are present
// and the type supports it; everything else keeps the proven JDK path.
if (proxyUser != null) {
when (type) {
"SOCKS5" -> return socks5Authenticated(host, port)
"HTTP" -> return httpConnectAuthenticated(host, port)
// SOCKS4 falls through to the JDK path (userid-only auth not
// supported here; see class doc).
}
}
val proxyAddress = InetSocketAddress(proxyHost, proxyPort)
val javaProxy = when (type) {
"SOCKS5", "SOCKS4" -> Proxy(Proxy.Type.SOCKS, proxyAddress)
"HTTP" -> Proxy(Proxy.Type.HTTP, proxyAddress)
else -> throw IOException("Unsupported proxy type: $proxyType")
}
val socket = Socket(javaProxy)
// Unresolved address so the proxy resolves the hostname remotely.
socket.connect(InetSocketAddress.createUnresolved(host, port), connectTimeoutMs)
return socket
}
/** SOCKS5 with RFC 1929 username/password auth (#227). */
private fun socks5Authenticated(host: String, port: Int): Socket {
val socket = Socket()
var ok = false
try {
socket.connect(InetSocketAddress(proxyHost, proxyPort), connectTimeoutMs)
socket.soTimeout = connectTimeoutMs
val out = socket.getOutputStream()
val ins = socket.getInputStream()
// Greeting: offer no-auth (0x00) and username/password (0x02).
out.write(byteArrayOf(0x05, 0x02, 0x00, 0x02))
out.flush()
val ver = readByte(ins)
if (ver != 0x05) throw IOException("SOCKS5 proxy bad version 0x${ver.toString(16)}")
when (val method = readByte(ins)) {
0x00 -> { /* server accepts no-auth */ }
0x02 -> {
// UTF-8 to match curl / JSch (str2byte) and what most SOCKS5
// servers store; the length octets below come from the byte
// arrays, so non-ASCII credentials stay correct (#227).
val u = (proxyUser ?: "").toByteArray(Charsets.UTF_8)
val p = (proxyPassword ?: "").toByteArray(Charsets.UTF_8)
if (u.size > 255 || p.size > 255) {
throw IOException("SOCKS5 proxy credentials exceed 255 bytes")
}
val auth = ByteArrayOutputStream()
auth.write(0x01) // auth subnegotiation version
auth.write(u.size); auth.write(u)
auth.write(p.size); auth.write(p)
out.write(auth.toByteArray())
out.flush()
readByte(ins) // auth version echo
if (readByte(ins) != 0x00) {
throw IOException("SOCKS5 proxy authentication failed (bad username/password)")
}
}
0xFF -> throw IOException("SOCKS5 proxy rejected the offered auth methods")
else -> throw IOException("SOCKS5 proxy requested unsupported auth method 0x${method.toString(16)}")
}
// CONNECT request, domain-name address type (remote DNS).
val dst = host.toByteArray(Charsets.ISO_8859_1)
if (dst.size > 255) throw IOException("SOCKS5 destination host too long")
val req = ByteArrayOutputStream()
req.write(0x05); req.write(0x01); req.write(0x00); req.write(0x03)
req.write(dst.size); req.write(dst)
req.write((port ushr 8) and 0xFF); req.write(port and 0xFF)
out.write(req.toByteArray())
out.flush()
if (readByte(ins) != 0x05) throw IOException("SOCKS5 proxy bad reply version")
val rep = readByte(ins)
if (rep != 0x00) throw IOException("SOCKS5 CONNECT failed (reply code $rep)")
readByte(ins) // RSV
when (val atyp = readByte(ins)) {
0x01 -> skipExact(ins, 4 + 2) // IPv4 + port
0x03 -> skipExact(ins, readByte(ins) + 2) // domain len + port
0x04 -> skipExact(ins, 16 + 2) // IPv6 + port
else -> throw IOException("SOCKS5 proxy bad reply ATYP 0x${atyp.toString(16)}")
}
socket.soTimeout = 0 // hand back a normal blocking socket
ok = true
return socket
} finally {
if (!ok) runCatching { socket.close() }
}
}
/** HTTP CONNECT with Proxy-Authorization: Basic (#227). */
private fun httpConnectAuthenticated(host: String, port: Int): Socket {
val socket = Socket()
var ok = false
try {
socket.connect(InetSocketAddress(proxyHost, proxyPort), connectTimeoutMs)
socket.soTimeout = connectTimeoutMs
val out = socket.getOutputStream()
val ins = socket.getInputStream()
val target = "$host:$port"
val token = java.util.Base64.getEncoder()
.encodeToString("${proxyUser ?: ""}:${proxyPassword ?: ""}".toByteArray(Charsets.UTF_8))
val request = buildString {
append("CONNECT ").append(target).append(" HTTP/1.1\r\n")
append("Host: ").append(target).append("\r\n")
append("Proxy-Authorization: Basic ").append(token).append("\r\n")
append("Proxy-Connection: keep-alive\r\n")
append("\r\n")
}
out.write(request.toByteArray(Charsets.ISO_8859_1))
out.flush()
val statusLine = readLine(ins)
?: throw IOException("HTTP proxy closed connection before CONNECT reply")
// Expect "HTTP/1.x 200 ..."; anything else (407, 403, 502) is failure.
val code = statusLine.split(' ').getOrNull(1)?.toIntOrNull()
if (code != 200) {
throw IOException("HTTP proxy CONNECT failed: $statusLine")
}
// Drain the remaining response headers up to the blank line.
while (true) {
val line = readLine(ins) ?: break
if (line.isEmpty()) break
}
socket.soTimeout = 0
ok = true
return socket
} finally {
if (!ok) runCatching { socket.close() }
}
}
private fun readByte(ins: InputStream): Int {
val b = ins.read()
if (b < 0) throw IOException("proxy closed connection unexpectedly")
return b and 0xFF
}
private fun skipExact(ins: InputStream, n: Int) {
var remaining = n
while (remaining > 0) {
val skipped = ins.skip(remaining.toLong())
if (skipped <= 0) {
if (ins.read() < 0) throw IOException("proxy closed connection unexpectedly")
remaining--
} else {
remaining -= skipped.toInt()
}
}
}
/** Reads a single CRLF- (or LF-) terminated line as ISO-8859-1; null at EOF. */
private fun readLine(ins: InputStream): String? {
val buf = ByteArrayOutputStream()
var sawAny = false
while (true) {
val b = ins.read()
if (b < 0) return if (sawAny) buf.toString("ISO-8859-1") else null
sawAny = true
if (b == '\n'.code) break
if (b != '\r'.code) buf.write(b)
}
return buf.toString("ISO-8859-1")
}
override fun createSocket(
host: String,
port: Int,
localHost: java.net.InetAddress?,
localPort: Int,
): Socket = createSocket(host, port)
override fun createSocket(host: java.net.InetAddress, port: Int): Socket =
createSocket(host.hostAddress ?: host.toString(), port)
override fun createSocket(
address: java.net.InetAddress,
port: Int,
localAddress: java.net.InetAddress?,
localPort: Int,
): Socket = createSocket(address, port)
}
@@ -0,0 +1,65 @@
package sh.haven.core.tunnel
import org.json.JSONObject
/**
* Storage envelope for Tailscale tunnel configs. Encoded into
* [sh.haven.core.data.db.entities.TunnelConfig.configText] (which is then
* encrypted at rest by the repository).
*
* The original v5.x storage format was the raw authkey bytes — useful
* when we only spoke to controlplane.tailscale.com, but unable to carry
* a Headscale URL alongside. v5.24.86 introduces a JSON envelope; old
* configs are still read back via [parse]'s legacy fallback so existing
* users don't have to re-add their tunnels.
*
* Format (UTF-8 JSON):
* ```
* { "authKey": "tskey-auth-…", "controlUrl": "https://headscale.example.com" }
* ```
*
* `controlUrl` is optional; absent or empty means the default Tailscale
* coordination server. Unknown JSON keys are ignored — adding fields
* (tags, hostname overrides) won't break older clients reading newer
* blobs.
*/
data class TailscaleConfigBlob(
val authKey: String,
val controlURL: String = "",
) {
fun encode(): ByteArray {
val json = JSONObject().apply {
put("authKey", authKey)
if (controlURL.isNotBlank()) put("controlUrl", controlURL)
}
return json.toString().toByteArray(Charsets.UTF_8)
}
companion object {
/**
* Decode bytes from [TunnelConfig.configText]. Tries JSON first;
* on parse failure or missing `authKey` field, treats the whole
* blob as the legacy raw-authkey format and returns a blob with
* an empty controlURL.
*/
fun parse(bytes: ByteArray): TailscaleConfigBlob {
val text = String(bytes, Charsets.UTF_8).trim()
if (text.startsWith("{")) {
try {
val json = JSONObject(text)
val authKey = json.optString("authKey", "").trim()
if (authKey.isNotEmpty()) {
return TailscaleConfigBlob(
authKey = authKey,
controlURL = json.optString("controlUrl", "").trim(),
)
}
} catch (_: Throwable) {
// fall through to legacy
}
}
// Legacy format: bytes are the raw authkey, no control URL.
return TailscaleConfigBlob(authKey = text)
}
}
}
@@ -0,0 +1,199 @@
package sh.haven.core.tunnel
import sh.haven.rclone.binding.tsbridge.Conn as NativeConn
import sh.haven.rclone.binding.tsbridge.Tsbridge
import sh.haven.rclone.binding.tsbridge.TunnelHandle as NativeHandle
import sh.haven.rclone.binding.tsbridge.UDPConn as NativeUDPConn
import java.io.File
import java.io.IOException
import java.io.InputStream
import java.io.InterruptedIOException
import java.io.OutputStream
import java.net.InetSocketAddress
/**
* [Tunnel] implementation backed by Tailscale's `tsnet` library via the
* gomobile-bound `tsbridge` package (co-located in rclone-android's Go
* module alongside wgbridge + rcbridge — see
* rclone-android/go/tsbridge/).
*
* Construction blocks until the tailnet connection is established (up to
* 30 seconds enforced on the Go side) — call on a background dispatcher.
*
* Unlike WireGuard's config blob, Tailscale auth is an authkey that's
* only consumed on first use; persistent node state lives in [stateDir]
* and is reused on subsequent starts of the same [TunnelConfig], so the
* authkey stays valid for its configured lifetime in the admin console.
*
* [controlURL] points at a self-hosted Headscale (or other compatible)
* coordination server; empty keeps the default controlplane.tailscale.com.
*/
class TailscaleTunnel internal constructor(
authKey: String,
stateDir: File,
hostname: String,
controlURL: String = "",
) : Tunnel {
private val native: NativeHandle = try {
Tsbridge.startTunnel(authKey, stateDir.absolutePath, hostname, controlURL)
} catch (e: Exception) {
throw IOException("Failed to start Tailscale tunnel: ${e.message}", e)
}
@Volatile
private var socksCached: InetSocketAddress? = null
override fun dial(host: String, port: Int, timeoutMs: Int): TunneledConnection {
val conn = try {
native.dial(host, port.toLong(), timeoutMs.toLong())
} catch (e: Exception) {
throw IOException("Tailscale dial $host:$port failed: ${e.message}", e)
}
return TailscaleConnection(conn)
}
override fun listenUdp(): TunneledDatagramSocket? {
val udp = try {
native.listenUDP()
} catch (e: Exception) {
throw IOException("Tailscale listenUDP failed: ${e.message}", e)
}
return TailscaleDatagramSocket(udp)
}
override fun socksAddress(): InetSocketAddress? {
socksCached?.let { return it }
return synchronized(this) {
socksCached?.let { return@synchronized it }
val port = try {
native.startSocksListener().toInt()
} catch (e: Exception) {
throw IOException("Tailscale SOCKS5 listener failed: ${e.message}", e)
}
InetSocketAddress("127.0.0.1", port).also { socksCached = it }
}
}
override fun close() {
try {
native.close()
} catch (_: Throwable) {
// Best-effort teardown.
}
}
}
/**
* Wraps a native [NativeConn] as [TunneledConnection]. Mirrors the
* WireGuard wrapper — gomobile copies `[]byte` across the JNI boundary,
* so `Conn.read(size)` returns a fresh slice each call and we copy into
* the caller's buffer in the [InputStream] shim.
*/
private class TailscaleConnection(
private val conn: NativeConn,
) : TunneledConnection {
override val remoteAddress: String?
get() = runCatching { conn.remoteAddrHost() }.getOrNull()?.takeIf { it.isNotBlank() }
override val inputStream: InputStream = object : InputStream() {
private var eof = false
override fun read(): Int {
val single = ByteArray(1)
val n = read(single, 0, 1)
return if (n == -1) -1 else single[0].toInt() and 0xFF
}
override fun read(b: ByteArray, off: Int, len: Int): Int {
if (eof) return -1
if (len == 0) return 0
val bytes = try {
conn.read(len.toLong())
} catch (_: Exception) {
eof = true
return -1
}
if (bytes == null || bytes.isEmpty()) {
eof = true
return -1
}
val n = minOf(bytes.size, len)
System.arraycopy(bytes, 0, b, off, n)
return n
}
}
override val outputStream: OutputStream = object : OutputStream() {
override fun write(b: Int) {
write(byteArrayOf((b and 0xFF).toByte()), 0, 1)
}
override fun write(b: ByteArray, off: Int, len: Int) {
val slice = if (off == 0 && len == b.size) b else b.copyOfRange(off, off + len)
try {
conn.write(slice)
} catch (e: Exception) {
throw IOException("Tailscale write failed: ${e.message}", e)
}
}
}
override fun close() {
try {
conn.close()
} catch (_: Throwable) { /* idempotent */ }
}
}
/**
* Wraps a native [NativeUDPConn] as [TunneledDatagramSocket]. Mirrors
* the WireGuard wrapper — same gomobile copy-out-of-fresh-slice pattern,
* same heuristic for translating Go's "i/o timeout" exception into a
* null return so the Mosh receive loop's contract holds for both
* backends.
*/
private class TailscaleDatagramSocket(
private val udp: NativeUDPConn,
) : TunneledDatagramSocket {
override fun send(data: ByteArray, host: String, port: Int) {
try {
udp.writeTo(data, host, port.toLong())
} catch (e: Exception) {
throw IOException("Tailscale UDP writeTo $host:$port failed: ${e.message}", e)
}
}
override fun receive(buf: ByteArray, timeoutMs: Int): ReceivedPacket? {
val result = try {
udp.readFrom(buf.size.toLong(), timeoutMs.toLong())
} catch (e: Exception) {
if (isTimeoutException(e)) return null
throw IOException("Tailscale UDP readFrom failed: ${e.message}", e)
}
if (result == null) return null
val bytes = result.data ?: return null
val n = minOf(bytes.size, buf.size)
System.arraycopy(bytes, 0, buf, 0, n)
return ReceivedPacket(
length = n,
srcHost = result.fromHost,
srcPort = result.fromPort.toInt(),
)
}
override fun close() {
try {
udp.close()
} catch (_: Throwable) { /* idempotent */ }
}
private fun isTimeoutException(e: Throwable): Boolean {
if (e is InterruptedIOException) return true
val msg = e.message ?: return false
return msg.contains("i/o timeout", ignoreCase = true) ||
msg.contains("deadline exceeded", ignoreCase = true)
}
}
@@ -0,0 +1,114 @@
package sh.haven.core.tunnel
import java.io.InputStream
import java.io.OutputStream
import java.net.InetSocketAddress
/**
* A userspace network tunnel. Implementations can be backed by WireGuard,
* Tailscale (follow-up), or any other backend that can produce a
* [TunneledConnection] for a `(host, port)` pair.
*
* Tunnels are expected to be reference-counted by a [TunnelManager] — the
* same tunnel handle may be used by multiple in-flight connections.
*/
interface Tunnel {
/**
* Dial a host through this tunnel. Must not block indefinitely — obey
* [timeoutMs] and throw on timeout. The returned [TunneledConnection] is
* owned by the caller and must be closed when done.
*/
fun dial(host: String, port: Int, timeoutMs: Int): TunneledConnection
/**
* Open an unconnected UDP socket through the tunnel. Caller supplies
* the destination on every send; the inbound source is surfaced on
* every receive. Returned socket is owned by the caller and must be
* closed when done.
*
* Default implementation returns null — backends that can't carry
* UDP (Cloudflare Access via websocket, SOCKS/HTTP legacy proxies)
* opt out by inheriting the default and the caller falls through to
* a raw [java.net.DatagramSocket].
*
* Used by Mosh (#164) so packets traverse the tunnel rather than
* the device's default route.
*/
fun listenUdp(): TunneledDatagramSocket? = null
/**
* Lazily start a localhost SOCKS5 listener fronting this tunnel and
* return its bound address (always 127.0.0.1, OS-assigned port).
* Idempotent — subsequent calls return the same address. Closing the
* tunnel also closes the listener.
*
* Used by transports that can't be intercepted at the Kotlin Socket
* layer (rclone via HTTPS_PROXY, IronRDP via a vendored SOCKS5
* client) so a single SOCKS5 endpoint fronts every TCP transport.
*
* Default implementation returns null — implementations that don't
* meaningfully expose a SOCKS surface (test fakes) opt out by
* inheriting the default.
*/
fun socksAddress(): InetSocketAddress? = null
/**
* Bind a TCP listener on the tunnel's own interface address inside the
* userspace netstack and return it, or null if the backend can't accept
* inbound connections. Lets an on-device server (the MCP endpoint, #176)
* accept connections from tunnel peers at [localAddress]:[port], stable
* across the device's WiFi/hotspot roams. Caller owns the returned
* socket and must close it. Closing the tunnel also tears it down.
*/
fun listenTcp(port: Int): TunneledServerSocket? = null
/**
* The tunnel's own interface address (the WireGuard `[Interface]`
* Address) — both the bind host for [listenTcp] and the host a peer
* dials to reach a server bound on it. Null when the backend has no
* meaningful local address.
*/
fun localAddress(): String? = null
/**
* Tear down the tunnel. All outstanding connections are invalidated.
* Idempotent.
*/
fun close()
}
/**
* An accepting socket bound inside a [Tunnel]'s netstack. Each [accept]
* blocks until a peer connects, returning a [TunneledConnection]. Mirrors
* [java.net.ServerSocket] without exposing a kernel socket.
*/
interface TunneledServerSocket {
/** Block until a peer connects. Throws [java.io.IOException] once closed. */
fun accept(): TunneledConnection
/** Stop accepting. Idempotent. Unblocks a pending [accept] with an error. */
fun close()
}
/**
* A byte-stream through a [Tunnel]. Mirrors [java.net.Socket] but without
* exposing a real [java.net.Socket] — our WireGuard implementation routes
* data through an in-process userspace netstack, not the kernel socket
* layer, so `getSocket()` on the JSch side returns null.
*/
interface TunneledConnection {
val inputStream: InputStream
val outputStream: OutputStream
/**
* The literal IP this connection was actually established to — the
* tunnel-resolved form of whatever name was dialled (Tailscale MagicDNS
* included), or null when the backend can't say. Callers that must
* satisfy an IP-literal contract (#539: the mosh UDP destination) use
* this instead of re-resolving the profile host in the wrong namespace.
*/
val remoteAddress: String? get() = null
/** Close the connection. Idempotent. */
fun close()
}
@@ -0,0 +1,33 @@
package sh.haven.core.tunnel
import dagger.Binds
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import okhttp3.OkHttpClient
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
abstract class TunnelHiltModule {
@Binds
@Singleton
abstract fun bindTunnelFactory(impl: DefaultTunnelFactory): TunnelFactory
companion object {
/**
* Shared OkHttp instance for the Cloudflare Access SSH backend.
* Per-dial call timeouts are set via `newBuilder()` in
* [CloudflareAccessTunnel.dial]; this base client deliberately
* leaves read/write timeouts at OkHttp's defaults (which
* effectively let a WebSocket stay open as long as the SSH
* session does) and stays idle when no Cloudflare Access
* tunnel is configured.
*/
@Provides
@Singleton
@JvmStatic
fun provideTunnelHttpClient(): OkHttpClient = OkHttpClient.Builder().build()
}
}
@@ -0,0 +1,236 @@
package sh.haven.core.tunnel
import android.content.Context
import android.util.Log
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import okhttp3.OkHttpClient
import sh.haven.core.data.db.entities.TunnelConfig
import sh.haven.core.data.db.entities.TunnelConfigType
import sh.haven.core.data.db.entities.typeEnum
import sh.haven.core.data.repository.TunnelConfigRepository
import java.io.File
import javax.inject.Inject
import javax.inject.Singleton
private const val TAG = "TunnelManager"
/**
* Constructs a live [Tunnel] from a stored [TunnelConfig]. Extracted
* behind an interface so tests can swap in fakes — production code goes
* through the native gomobile bridges, which can't be exercised from a
* JVM-only unit test without Robolectric.
*/
interface TunnelFactory {
fun create(config: TunnelConfig): Tunnel
}
/**
* Resolves a [TunnelConfig] (stored by id on a connection profile) into a
* usable [Tunnel] and reference-counts the result so multiple profiles
* sharing the same config share a single live tunnel handle.
*
* **Lifecycle:**
* - [acquire] gets-or-creates the [Tunnel] for the given config and
* records `profileId` as a dependent. Idempotent for the same
* `(configId, profileId)` pair.
* - [release] removes a dependent. The tunnel is torn down only when
* its last dependent releases. Releasing a profile that never
* acquired is a no-op.
* - If a profile re-acquires with a *different* config without
* releasing first, the prior slot is auto-released. Useful for the
* edge case of a user editing `tunnelConfigId` on a live profile.
*
* **Why this matters:** WireGuard handshakes take 1–2 s and Tailscale's
* tsnet startup blocks up to 30 s. Without refcounting, a transport
* tearing down its connection would close the handle out from under any
* sibling transport sharing the same config (e.g. SSH + VNC in a
* workspace profile both routed through one WireGuard tunnel).
*
* Dispatches by [TunnelConfigType.type]:
* - [TunnelConfigType.WIREGUARD] → [WireguardTunnel] (wireguard-go +
* gVisor netstack, bundled into libgojni.so).
* - [TunnelConfigType.TAILSCALE] → [TailscaleTunnel] (tsnet, same .so).
*
* Tailscale needs a per-config writable state directory for node keys +
* cert cache. Created under `<filesDir>/tailscale-<configId>/` the first
* time a given config is started and reused on subsequent starts so the
* authkey is only consumed once.
*/
@Singleton
class TunnelManager @Inject constructor(
private val tunnelConfigRepository: TunnelConfigRepository,
private val tunnelFactory: TunnelFactory,
) {
private val mutex = Mutex()
private val liveTunnels = mutableMapOf<String, Tunnel>()
/** configId → set of profileIds currently depending on this tunnel. */
private val dependents = mutableMapOf<String, MutableSet<String>>()
/** profileId → the configId it last acquired. One tunnel per profile, mirroring the data model. */
private val acquiredBy = mutableMapOf<String, String>()
/**
* Get-or-create the tunnel for [configId] and register [profileId] as
* a dependent. Returns null if the config was deleted from storage —
* callers should treat that as "fall through to direct dialling".
*
* Idempotent: re-acquiring with the same (configId, profileId) pair
* returns the same tunnel and leaves the dependent set unchanged.
*
* If [profileId] previously acquired a *different* config, that prior
* slot is auto-released first (and its tunnel torn down if it had no
* other dependents). Profiles only ever hold one tunnel at a time.
*/
suspend fun acquire(configId: String, profileId: String): Tunnel? {
var staleToClose: Tunnel? = null
val acquired = mutex.withLock {
val previous = acquiredBy[profileId]
if (previous != null && previous != configId) {
Log.w(TAG, "Profile $profileId switching tunnel $previous → $configId without explicit release; auto-releasing prior")
staleToClose = internalRelease(previous, profileId)
}
val tunnel = liveTunnels[configId] ?: run {
val config = tunnelConfigRepository.getById(configId) ?: return@withLock null
tunnelFactory.create(config).also { liveTunnels[configId] = it }
}
dependents.getOrPut(configId) { mutableSetOf() }.add(profileId)
acquiredBy[profileId] = configId
tunnel
}
staleToClose?.close()
return acquired
}
/**
* Release whatever tunnel [profileId] currently holds. Tears down the
* underlying tunnel only if this was its last dependent. No-op if the
* profile has no live acquire.
*
* The actual tunnel close happens *outside* the manager's lock — close
* may make a native call (gomobile) and we don't want to hold the lock
* for that.
*/
suspend fun release(profileId: String) {
val toClose = mutex.withLock {
val configId = acquiredBy[profileId] ?: return@withLock null
internalRelease(configId, profileId)
}
toClose?.close()
}
/**
* Caller must hold [mutex]. Returns the [Tunnel] that should be closed
* outside the lock if this drained the dependent set, or null otherwise.
*/
private fun internalRelease(configId: String, profileId: String): Tunnel? {
acquiredBy.remove(profileId)
val deps = dependents[configId] ?: return null
deps.remove(profileId)
if (deps.isEmpty()) {
dependents.remove(configId)
return liveTunnels.remove(configId)
}
return null
}
/**
* Register [profileId] as a dependent of whichever WireGuard tunnel is
* currently live (the first, if several) and return it — or null if no
* WireGuard tunnel is up. Used by the MCP server (#176) to bind its
* endpoint listener on an already-active WG tunnel and keep that tunnel
* alive (via the refcount) for as long as MCP is bound, even after the
* profile that originally brought it up disconnects. Release with the
* same [profileId] via [release].
*/
suspend fun acquireFirstWireguard(profileId: String): Tunnel? = mutex.withLock {
val entry = liveTunnels.entries.firstOrNull { it.value is WireguardTunnel }
?: return@withLock null
val configId = entry.key
// A synthetic MCP profileId only ever holds this one tunnel, so the
// acquiredBy bookkeeping mirrors the normal acquire path.
dependents.getOrPut(configId) { mutableSetOf() }.add(profileId)
acquiredBy[profileId] = configId
entry.value
}
/** Test / introspection — number of live dependents on the given config. */
suspend fun dependentCount(configId: String): Int = mutex.withLock {
dependents[configId]?.size ?: 0
}
/**
* True iff at least one WireGuard tunnel is currently live. The MCP
* reverse-tunnel manager gates on this to stand its (redundant, fragile)
* SSH `-R` down while WireGuard is exposing the MCP endpoint directly, and
* to revive the `-R` fallback if the WG tunnel later drops.
*/
suspend fun hasLiveWireguard(): Boolean = mutex.withLock {
liveTunnels.values.any { it is WireguardTunnel }
}
/**
* Snapshot of the live tunnel state — every configId that currently
* has at least one active dependent, paired with the set of profile
* ids holding it. For agent / debug tooling that wants to verify
* refcount semantics end-to-end (#149 integration tests).
*/
suspend fun liveSnapshot(): List<LiveTunnelEntry> = mutex.withLock {
dependents
.filterValues { it.isNotEmpty() }
.map { (configId, deps) -> LiveTunnelEntry(configId, deps.toSet()) }
}
}
/** A live tunnel as visible to introspection: the config it came from, and the profiles depending on it. */
data class LiveTunnelEntry(
val configId: String,
val dependentProfileIds: Set<String>,
)
/**
* Production [TunnelFactory] — dispatches by config type and wires up
* per-config Tailscale state directories under the app's private files
* dir. Hilt-provides the singleton; tests construct [TunnelManager]
* directly with their own factory.
*/
@Singleton
class DefaultTunnelFactory @Inject constructor(
@ApplicationContext private val context: Context,
private val httpClient: OkHttpClient,
) : TunnelFactory {
override fun create(config: TunnelConfig): Tunnel = when (config.typeEnum) {
TunnelConfigType.WIREGUARD -> WireguardTunnel(String(config.configText))
TunnelConfigType.TAILSCALE -> {
val parsed = TailscaleConfigBlob.parse(config.configText)
TailscaleTunnel(
authKey = parsed.authKey,
stateDir = File(context.filesDir, "tailscale-${config.id}").also { it.mkdirs() },
hostname = deriveHostname(config.label),
controlURL = parsed.controlURL,
)
}
TunnelConfigType.CLOUDFLARE_ACCESS -> {
val parsed = CloudflareAccessConfigBlob.parse(config.configText)
CloudflareAccessTunnel(
hostname = parsed.hostname,
jwt = parsed.jwt,
jumpDestination = parsed.jumpDestination,
httpClient = httpClient,
)
}
}
/**
* Tailscale nodes appear in the tailnet admin console by hostname.
* Derive from the config label so users can tell their entries apart;
* sanitise to DNS-compatible characters because Tailscale enforces that.
*/
private fun deriveHostname(label: String): String {
val safe = label.lowercase()
.map { if (it.isLetterOrDigit()) it else '-' }
.joinToString("")
.trim('-')
return if (safe.isBlank()) "haven-android" else "haven-$safe"
}
}
@@ -0,0 +1,59 @@
package sh.haven.core.tunnel
import com.jcraft.jsch.Proxy
import com.jcraft.jsch.SocketFactory
import java.io.InputStream
import java.io.OutputStream
import java.net.Socket
import sh.haven.core.ssh.TunnelPeerAware
/**
* JSch [Proxy] adapter over a [Tunnel]. JSch hands us `(host, port)` at
* connect time; we dial through the tunnel and surface the resulting
* streams. `getSocket()` returns null — our connections are not backed by
* a kernel socket (see [TunneledConnection]), and [Proxy] contract allows
* null there.
*
* Mirrors the shape of [sh.haven.core.ssh.ProxyJump] — the existing JSch
* proxy for jump-host tunneling. Same lifecycle (`connect` → stream I/O →
* `close`), just a different source of bytes.
*/
class TunnelProxy(private val tunnel: Tunnel) : Proxy, TunnelPeerAware {
private var connection: TunneledConnection? = null
/**
* The tunnel-resolved peer IP of the most recent [connect] (#539) —
* what the tailnet/netstack actually dialled, MagicDNS names included.
* Null before connect or when the backend can't report it.
*/
override val tunnelPeerAddress: String?
get() = connection?.remoteAddress
override fun connect(factory: SocketFactory?, host: String, port: Int, timeout: Int) {
// Tunnels need more headroom than a direct TCP SYN — peer session
// setup (WireGuard handshake, magicsock NAT punch, DERP fallback,
// MagicDNS lookups) can burn 1-2 s before application traffic
// flows. JSch's default 10 s connect timeout often isn't enough
// on first dial to a cold peer. Clamp to at least 30 s.
val effectiveTimeout = maxOf(timeout, TUNNEL_MIN_DIAL_TIMEOUT_MS)
connection = tunnel.dial(host, port, effectiveTimeout)
}
override fun getInputStream(): InputStream =
connection?.inputStream ?: error("TunnelProxy.connect() not called")
override fun getOutputStream(): OutputStream =
connection?.outputStream ?: error("TunnelProxy.connect() not called")
override fun getSocket(): Socket? = null
override fun close() {
connection?.close()
connection = null
}
private companion object {
const val TUNNEL_MIN_DIAL_TIMEOUT_MS = 30_000
}
}
@@ -0,0 +1,254 @@
package sh.haven.core.tunnel
import com.jcraft.jsch.ProxyHTTP
import com.jcraft.jsch.ProxySOCKS4
import com.jcraft.jsch.ProxySOCKS5
import sh.haven.core.data.db.entities.ConnectionProfile
import sh.haven.core.ssh.HavenProxy
import java.net.InetSocketAddress
import javax.inject.Inject
import javax.inject.Singleton
import javax.net.SocketFactory
/**
* Single dispatch point for "how does this connection profile reach the
* network?". Replaces ad-hoc `if (profile.tunnelConfigId != null) ...`
* checks scattered across per-transport viewmodels.
*
* Three surfaces, each picked by the consumer based on what its transport
* library can accept:
*
* - [dial] — direct in-process [TunneledConnection]. Simplest path; for
* transports that own their socket creation in Kotlin (VNC, Reticulum).
* - [socketFactory] — javax.net.SocketFactory wrapping the same tunnel.
* For transports that take a factory (smbj's SmbConfig).
* - [socksEndpoint] — localhost SOCKS5 listener address. For transports
* behind FFI (rclone gomobile, IronRDP Rust) that can talk SOCKS5 but
* can't have their socket creation intercepted from Kotlin. Currently
* returns null; wired up when [Tunnel.socksAddress] (and the matching
* Go / tsnet listener) lands.
*
* All three return null when the profile has no tunnel selected — the
* caller falls through to dialling a real Socket directly.
*
* A fourth surface, [havenProxy], is for SSH consumers. It wraps the
* tunnel as an opaque [HavenProxy] (over JSch's `Proxy` for now) and
* *also* honours the legacy `proxyType`/`proxyHost`/`proxyPort` columns
* on [ConnectionProfile] (SOCKS5 / SOCKS4 / HTTP). [dial] and
* [socketFactory] don't yet honour
* the SOCKS columns; that will land alongside non-SSH transport adoption
* (step 7 of #149).
*/
@Singleton
class TunnelResolver @Inject constructor(
private val tunnelManager: TunnelManager,
) {
suspend fun dial(
profile: ConnectionProfile,
host: String,
port: Int,
timeoutMs: Int,
): TunneledConnection? {
tunnelFor(profile)?.let { return it.dial(host, port, timeoutMs) }
// Fall through to legacy SOCKS / HTTP proxy if configured.
proxySocketFactoryFor(profile, timeoutMs)?.let { factory ->
val socket = factory.createSocket(host, port)
return SocketTunneledConnection(socket)
}
return null
}
suspend fun socketFactory(profile: ConnectionProfile): SocketFactory? {
tunnelFor(profile)?.let { return TunnelSocketFactory(it) }
return proxySocketFactoryFor(profile)
}
/**
* Resolve a UDP transport for [profile]. Returns a
* [TunneledDatagramSocket] when the profile selects a tunnel that
* can carry UDP (WireGuard, Tailscale); returns null when no tunnel
* is selected or the selected backend can't carry UDP (Cloudflare
* Access, legacy SOCKS/HTTP proxies — UDP ASSOCIATE is not
* supported here). Callers fall through to a plain
* [java.net.DatagramSocket] on null.
*
* Acquires the tunnel via [tunnelManager]; pair with [release] on
* the [ConnectionProfile.id] when the UDP socket is closed, same
* lifecycle contract as [dial].
*
* One-shot use. For callers that need to mint a fresh tunneled
* socket on every Mosh roaming-rebind, see [udpSocketSupplier].
*/
suspend fun dialUdp(profile: ConnectionProfile): TunneledDatagramSocket? {
val tunnel = tunnelFor(profile) ?: return null
return tunnel.listenUdp()
}
/**
* Pre-acquire the tunnel and return a non-suspend factory that
* mints a fresh [TunneledDatagramSocket] each call. Mirrors
* [socketDialer] for UDP. Mosh's rebind path calls the factory
* each time the upstream socket goes stale; the underlying tunnel
* handle is reused across rebinds.
*
* Returns null when the profile has no tunnel or the tunnel can't
* carry UDP — caller falls through to a raw
* [java.net.DatagramSocket] (same behaviour as today's Mosh).
*
* The factory throws [java.io.IOException] if the tunnel was torn
* down between acquisition and a rebind attempt (e.g. user toggled
* the tunnel off mid-session). [MoshConnection.rebindSocket] swallows
* that failure and keeps the current socket, so the send loop survives
* and the next stall cycle retries once the tunnel is back (#421).
*/
suspend fun udpSocketSupplier(
profile: ConnectionProfile,
): (() -> TunneledDatagramSocket)? {
val tunnel = tunnelFor(profile) ?: return null
return {
tunnel.listenUdp() ?: throw java.io.IOException(
"Tunnel ${profile.tunnelConfigId} does not support UDP",
)
}
}
suspend fun socksEndpoint(profile: ConnectionProfile): InetSocketAddress? {
val tunnel = tunnelFor(profile) ?: return null
return tunnel.socksAddress()
}
/**
* Proxy / tunnel chain for a profile, as an opaque [HavenProxy] that
* `SshClient` consumes. WireGuard / Tailscale tunnel takes precedence
* over the legacy `proxyType` columns; both are mutually exclusive at
* the UI level. Returns null for direct dialling.
*
* Does **not** handle SSH jump-host — that needs a live SSH session,
* so callers resolve it before delegating here.
*/
suspend fun havenProxy(profile: ConnectionProfile): HavenProxy? =
jschProxy(profile)?.let(::HavenProxy)
/**
* Test-only accessor returning the underlying JSch `Proxy` so unit tests
* can assert the proxy variant (`TunnelProxy` / `ProxySOCKS5` / etc.).
* Production code uses [havenProxy] instead.
*/
internal suspend fun jschProxy(profile: ConnectionProfile): com.jcraft.jsch.Proxy? {
tunnelFor(profile)?.let { return TunnelProxy(it) }
val proxyHost = profile.proxyHost ?: return null
// #227: when the proxy requires authentication, JSch throws
// JSchProxyException("…username/password authentication requested by
// server with no username/password configured") unless we call
// setUserPasswd before the proxy handshake runs. SOCKS4 only carries
// a userid (password ignored); SOCKS5 uses RFC 1929 user/pass; HTTP
// uses Proxy-Authorization: Basic.
val user = profile.proxyUser?.takeIf { it.isNotEmpty() }
val pass = profile.proxyPassword ?: ""
return when (profile.proxyType) {
// #227: an authenticated SOCKS5 proxy goes through ProxySocketFactory
// (byte-correct RFC 1929) rather than JSch's ProxySOCKS5, whose
// username/password length octets use the character count, corrupting
// non-ASCII credentials. No-auth SOCKS5 keeps JSch's proxy unchanged.
"SOCKS5" ->
if (user != null) {
AuthenticatedProxy(
ProxySocketFactory(
proxyType = "SOCKS5",
proxyHost = proxyHost,
proxyPort = profile.proxyPort,
proxyUser = user,
proxyPassword = pass,
),
)
} else {
ProxySOCKS5(proxyHost, profile.proxyPort)
}
// SOCKS4 sends a NUL-terminated userid (no length octet → no
// char/byte mismatch) and HTTP Basic base64s the raw UTF-8 bytes;
// both are byte-correct in JSch, so they stay on JSch's proxies.
"SOCKS4" -> ProxySOCKS4(proxyHost, profile.proxyPort).apply {
if (user != null) setUserPasswd(user, pass)
}
"HTTP" -> ProxyHTTP(proxyHost, profile.proxyPort).apply {
if (user != null) setUserPasswd(user, pass)
}
else -> null
}
}
/**
* Release the tunnel acquired for [profileId]. Pair with any prior
* call that returned a non-null result from [dial], [socketFactory],
* [socketDialer], or [havenProxy]. Idempotent — safe to call on
* disconnect even if the profile never acquired anything.
*/
suspend fun release(profileId: String) {
tunnelManager.release(profileId)
}
/**
* Returns a non-suspend dialer closure that the caller invokes once
* per TCP connection — useful for libraries that own their socket
* lifecycle and dial outside a coroutine context (reticulum-kt's
* `TCPClientInterface`, for example). The tunnel is acquired
* up-front; subsequent dials reuse the same handle.
*
* Returns null when the profile has neither a tunnel nor a proxy
* configured — caller falls through to its default `Socket()` dial.
*/
suspend fun socketDialer(
profile: ConnectionProfile,
): ((String, Int, Int) -> java.net.Socket)? {
tunnelFor(profile)?.let { tunnel ->
return { host, port, timeoutMs ->
val conn = tunnel.dial(host, port, timeoutMs)
TunneledSocket(conn, host, port)
}
}
proxySocketFactoryFor(profile)?.let { factory ->
return { host, port, _ ->
factory.createSocket(host, port)
}
}
return null
}
private suspend fun tunnelFor(profile: ConnectionProfile): Tunnel? {
val tunnelId = profile.tunnelConfigId ?: return null
return tunnelManager.acquire(tunnelId, profile.id)
}
private fun proxySocketFactoryFor(
profile: ConnectionProfile,
timeoutMs: Int = 30_000,
): ProxySocketFactory? {
val type = profile.proxyType ?: return null
val host = profile.proxyHost ?: return null
return ProxySocketFactory(
proxyType = type,
proxyHost = host,
proxyPort = profile.proxyPort,
connectTimeoutMs = timeoutMs,
proxyUser = profile.proxyUser?.takeIf { it.isNotEmpty() },
proxyPassword = profile.proxyPassword,
)
}
}
/**
* Adapts a [Socket] (typically returned by [ProxySocketFactory]) to the
* [TunneledConnection] interface so callers of [TunnelResolver.dial]
* see a uniform shape regardless of whether the routing layer is a
* userspace tunnel or a JDK-style proxy.
*/
private class SocketTunneledConnection(
private val socket: java.net.Socket,
) : TunneledConnection {
override val inputStream: java.io.InputStream = socket.getInputStream()
override val outputStream: java.io.OutputStream = socket.getOutputStream()
override fun close() {
try { socket.close() } catch (_: Throwable) { /* best-effort */ }
}
}
@@ -0,0 +1,56 @@
package sh.haven.core.tunnel
import java.net.InetAddress
import java.net.Socket
import javax.net.SocketFactory
/**
* javax.net.SocketFactory that dials through a [Tunnel] and returns the
* resulting connection wrapped as a [TunneledSocket].
*
* Used where an upstream library takes a SocketFactory rather than a
* pre-dialled Socket — currently smbj via `SmbConfig.builder()
* .withSocketFactory(...)`.
*
* @param dialTimeoutMs timeout passed to [Tunnel.dial]. Default 30 s
* matches [TunnelProxy]'s floor: WireGuard / Tailscale handshakes
* take 1–2 s before application traffic, and many upstream consumers
* pass shorter SO_TIMEOUT-style values that would prematurely fail.
*/
class TunnelSocketFactory(
private val tunnel: Tunnel,
private val dialTimeoutMs: Int = 30_000,
) : SocketFactory() {
/**
* Unconnected socket whose dial is deferred to [Socket.connect]. JavaMail's
* SocketFetcher creates the base socket via the no-arg `createSocket()` and
* then calls `connect(addr)`, so a connected-only factory can't serve it
* (it hits SocketFactory's "Unconnected sockets not implemented" default).
* [DeferredTunneledSocket] bridges that, dialing through the tunnel on
* connect — so a dead tunnel fails the connect (no clearnet fallback).
*/
override fun createSocket(): Socket = DeferredTunneledSocket(tunnel, dialTimeoutMs)
override fun createSocket(host: String, port: Int): Socket {
val conn = tunnel.dial(host, port, dialTimeoutMs)
return TunneledSocket(conn, host, port)
}
override fun createSocket(
host: String,
port: Int,
localHost: InetAddress?,
localPort: Int,
): Socket = createSocket(host, port)
override fun createSocket(host: InetAddress, port: Int): Socket =
createSocket(host.hostAddress ?: host.toString(), port)
override fun createSocket(
address: InetAddress,
port: Int,
localAddress: InetAddress?,
localPort: Int,
): Socket = createSocket(address, port)
}
@@ -0,0 +1,59 @@
package sh.haven.core.tunnel
/**
* A UDP socket routed through a [Tunnel]. Mirrors the subset of
* [java.net.DatagramSocket] that Mosh (and any other unconnected-UDP
* transport) actually uses: send-to / receive-from / close, with a
* per-call read timeout.
*
* Implementations are unconnected — every [send] carries an explicit
* destination, and [receive] surfaces the source of each datagram.
* Mosh's "client roams, server identifies by SSP nonce" model maps
* directly onto this; if a future caller wants connected semantics, it
* can pin the destination at the wrapper level rather than down here.
*
* Not thread-safe by contract. Callers that send and receive from
* different threads (Mosh's send/receive coroutines) must coordinate
* externally — `MoshConnection` already does this via its `socketLock`.
*/
interface TunneledDatagramSocket {
/**
* Send [data] to `host:port` through the tunnel. host must be a
* literal IP — the bridge layer rejects hostnames so DNS lookups
* can't happen on the per-packet path. Mosh always knows the
* server IP from the SSH bootstrap's MOSH CONNECT line, so this
* is never a constraint in practice.
*/
fun send(data: ByteArray, host: String, port: Int)
/**
* Block until a datagram arrives or [timeoutMs] expires.
*
* Returns `null` on timeout — the same convention
* [java.net.DatagramSocket.receive] communicates via
* [java.net.SocketTimeoutException], translated to null here so the
* Mosh receive loop doesn't have to catch in two places. `timeoutMs`
* `<= 0` blocks indefinitely.
*
* On a successful receive, the caller-supplied [buf] is populated
* from index 0 with up to [ReceivedPacket.length] bytes. If the
* datagram is larger than [buf] it is truncated — same as
* [java.net.DatagramSocket] with an under-sized [java.net.DatagramPacket].
*
* Throws on transport failure (socket closed, tunnel torn down).
*/
fun receive(buf: ByteArray, timeoutMs: Int): ReceivedPacket?
/** Close the socket. Idempotent. */
fun close()
}
/**
* Result of a successful [TunneledDatagramSocket.receive]. Mirrors the
* fields of [java.net.DatagramPacket] that callers actually read.
*/
data class ReceivedPacket(
val length: Int,
val srcHost: String,
val srcPort: Int,
)
@@ -0,0 +1,245 @@
package sh.haven.core.tunnel
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.net.InetAddress
import java.net.InetSocketAddress
import java.net.Socket
import java.net.SocketAddress
/**
* java.net.Socket adapter backed by a [TunneledConnection].
*
* Userspace tunnels (WireGuard / Tailscale) don't expose kernel sockets;
* a [TunneledConnection] is the byte-stream surface they offer instead.
* Some upstream libraries hard-code a Socket dependency though — VNC's
* VeNCrypt upgrade calls `SSLSocketFactory.createSocket(socket, host,
* port, true)` (the layered-SSL form) and smbj's SmbConfig takes a
* javax.net.SocketFactory whose contract returns Sockets. This class
* bridges both: hand a TunneledSocket to those APIs and they read/write
* via the underlying TunneledConnection.
*
* The connection is pre-dialled — [connect] and [bind] therefore throw
* [UnsupportedOperationException]. [close] is idempotent.
*/
class TunneledSocket(
private val connection: TunneledConnection,
private val host: String,
private val port: Int,
) : Socket() {
@Volatile
private var closed: Boolean = false
override fun getInputStream(): InputStream {
if (closed) throw IOException("Socket is closed")
return connection.inputStream
}
override fun getOutputStream(): OutputStream {
if (closed) throw IOException("Socket is closed")
return connection.outputStream
}
override fun getInetAddress(): InetAddress? {
// #539: answer from the tunnel's namespace when it can say what it
// actually connected to. InetAddress.getByName(host) resolves through
// the PHONE's resolver — a different namespace from the tunnel's
// (MagicDNS), so its answer can be wrong or absent. getByName on a
// literal never touches DNS.
return try {
InetAddress.getByName(connection.remoteAddress ?: host)
} catch (_: Exception) {
null
}
}
override fun getPort(): Int = port
override fun getLocalAddress(): InetAddress = InetAddress.getLoopbackAddress()
override fun getLocalPort(): Int = -1
override fun isConnected(): Boolean = !closed
override fun isBound(): Boolean = false
override fun isClosed(): Boolean = closed
override fun isInputShutdown(): Boolean = closed
override fun isOutputShutdown(): Boolean = closed
override fun close() {
if (closed) return
closed = true
try {
connection.close()
} catch (_: Throwable) {
// best-effort teardown
}
}
override fun connect(endpoint: SocketAddress?) {
throw UnsupportedOperationException("TunneledSocket is pre-connected")
}
override fun connect(endpoint: SocketAddress?, timeout: Int) {
throw UnsupportedOperationException("TunneledSocket is pre-connected")
}
override fun bind(bindpoint: SocketAddress?) {
throw UnsupportedOperationException("TunneledSocket cannot be bound")
}
override fun shutdownInput() {
// No-op — userspace tunnels don't expose half-close.
}
override fun shutdownOutput() {
// No-op — userspace tunnels don't expose half-close.
}
// TCP-level socket options below — userspace tunnels (WireGuard /
// Tailscale) handle their own buffering, keepalives, and shutdown
// semantics inside the netstack, so kernel-socket knobs have no
// backing implementation. We accept-and-ignore rather than throw,
// because callers like reticulum-kt's TCPClientInterface set these
// unconditionally on every dial.
override fun setTcpNoDelay(on: Boolean) { /* no-op */ }
override fun setKeepAlive(on: Boolean) { /* no-op */ }
override fun setSoTimeout(timeout: Int) { /* no-op */ }
override fun setSoLinger(on: Boolean, linger: Int) { /* no-op */ }
override fun setReuseAddress(on: Boolean) { /* no-op */ }
override fun setOOBInline(on: Boolean) { /* no-op */ }
override fun setReceiveBufferSize(size: Int) { /* no-op */ }
override fun setSendBufferSize(size: Int) { /* no-op */ }
override fun setTrafficClass(tc: Int) { /* no-op */ }
override fun getTcpNoDelay(): Boolean = false
override fun getKeepAlive(): Boolean = false
override fun getSoTimeout(): Int = 0
override fun getSoLinger(): Int = -1
override fun getReuseAddress(): Boolean = false
override fun getOOBInline(): Boolean = false
override fun getRemoteSocketAddress(): java.net.SocketAddress? {
// Resolved from the tunnel's own report when available (#539);
// otherwise the unresolved holder it always was.
val peer = connection.remoteAddress ?: return java.net.InetSocketAddress.createUnresolved(host, port)
return try {
java.net.InetSocketAddress(InetAddress.getByName(peer), port)
} catch (_: Exception) {
java.net.InetSocketAddress.createUnresolved(host, port)
}
}
}
/**
* Like [TunneledSocket] but dials the tunnel lazily on [connect] rather than
* wrapping a pre-dialled connection. Required by upstream libraries that obtain
* a socket from a [javax.net.SocketFactory] via the no-arg `createSocket()` and
* then call `connect(addr)` — notably JavaMail's `SocketFetcher`, which uses
* that pattern for any custom base socket factory. A dead/blocked tunnel makes
* the [connect] dial fail, so the caller fails closed (no clearnet fallback).
*/
class DeferredTunneledSocket(
private val tunnel: Tunnel,
private val dialTimeoutMs: Int,
) : Socket() {
@Volatile
private var connection: TunneledConnection? = null
@Volatile
private var host: String = ""
@Volatile
private var port: Int = -1
@Volatile
private var closed: Boolean = false
override fun connect(endpoint: SocketAddress?) = connect(endpoint, 0)
override fun connect(endpoint: SocketAddress?, timeout: Int) {
if (closed) throw IOException("Socket is closed")
val addr = endpoint as? InetSocketAddress
?: throw IOException("Unsupported endpoint: $endpoint")
host = addr.hostString ?: addr.address?.hostAddress
?: throw IOException("Unresolved endpoint host")
port = addr.port
connection = tunnel.dial(host, port, if (timeout > 0) timeout else dialTimeoutMs)
}
private fun conn(): TunneledConnection {
if (closed) throw IOException("Socket is closed")
return connection ?: throw IOException("Socket is not connected")
}
override fun getInputStream(): InputStream = conn().inputStream
override fun getOutputStream(): OutputStream = conn().outputStream
override fun getInetAddress(): InetAddress? = try {
InetAddress.getByName(host)
} catch (_: Exception) {
null
}
override fun getPort(): Int = port
override fun getLocalAddress(): InetAddress = InetAddress.getLoopbackAddress()
override fun getLocalPort(): Int = -1
override fun isConnected(): Boolean = connection != null && !closed
override fun isBound(): Boolean = connection != null
override fun isClosed(): Boolean = closed
override fun isInputShutdown(): Boolean = closed
override fun isOutputShutdown(): Boolean = closed
override fun close() {
if (closed) return
closed = true
try {
connection?.close()
} catch (_: Throwable) {
// best-effort teardown
}
}
override fun bind(bindpoint: SocketAddress?) {
// No-op — the tunnel binds its own source on dial.
}
override fun shutdownInput() {}
override fun shutdownOutput() {}
// Socket options — same accept-and-ignore contract as [TunneledSocket].
override fun setTcpNoDelay(on: Boolean) {}
override fun setKeepAlive(on: Boolean) {}
override fun setSoTimeout(timeout: Int) {}
override fun setSoLinger(on: Boolean, linger: Int) {}
override fun setReuseAddress(on: Boolean) {}
override fun setOOBInline(on: Boolean) {}
override fun setReceiveBufferSize(size: Int) {}
override fun setSendBufferSize(size: Int) {}
override fun setTrafficClass(tc: Int) {}
override fun getTcpNoDelay(): Boolean = false
override fun getKeepAlive(): Boolean = false
override fun getSoTimeout(): Int = 0
override fun getSoLinger(): Int = -1
override fun getReuseAddress(): Boolean = false
override fun getOOBInline(): Boolean = false
override fun getRemoteSocketAddress(): SocketAddress? =
if (port >= 0) InetSocketAddress.createUnresolved(host, port) else null
}
@@ -0,0 +1,288 @@
package sh.haven.core.tunnel
import sh.haven.rclone.binding.wgbridge.Conn as NativeConn
import sh.haven.rclone.binding.wgbridge.Listener as NativeListener
import sh.haven.rclone.binding.wgbridge.TunnelHandle as NativeHandle
import sh.haven.rclone.binding.wgbridge.UDPConn as NativeUDPConn
import sh.haven.rclone.binding.wgbridge.Wgbridge
import java.io.IOException
import java.io.InputStream
import java.io.InterruptedIOException
import java.io.OutputStream
import java.net.InetSocketAddress
/**
* [Tunnel] implementation backed by wireguard-go + gVisor netstack via
* the gomobile-bound `wgbridge` package (co-located in rclone-android so
* both gomobile bindings ship in a single `libgojni.so` — see
* rclone-android/go/wgbridge/).
*
* Holds one live native tunnel handle — created up-front from the user's
* wg-quick config text, torn down on [close]. Dials are safe to call
* concurrently; the native layer serialises as needed.
*/
class WireguardTunnel internal constructor(configText: String) : Tunnel {
private val native: NativeHandle = try {
Wgbridge.startTunnel(ensurePeerKeepalive(configText))
} catch (e: Exception) {
throw IOException("Failed to start WireGuard tunnel: ${e.message}", e)
}
@Volatile
private var socksCached: InetSocketAddress? = null
override fun dial(host: String, port: Int, timeoutMs: Int): TunneledConnection {
val conn = try {
native.dial(host, port.toLong(), timeoutMs.toLong())
} catch (e: Exception) {
throw IOException("WireGuard dial $host:$port failed: ${e.message}", e)
}
return NativeTunneledConnection(conn)
}
override fun listenUdp(): TunneledDatagramSocket? {
val udp = try {
native.listenUDP()
} catch (e: Exception) {
throw IOException("WireGuard listenUDP failed: ${e.message}", e)
}
return NativeTunneledDatagramSocket(udp)
}
override fun socksAddress(): InetSocketAddress? {
socksCached?.let { return it }
return synchronized(this) {
socksCached?.let { return@synchronized it }
val port = try {
native.startSocksListener().toInt()
} catch (e: Exception) {
throw IOException("WireGuard SOCKS5 listener failed: ${e.message}", e)
}
InetSocketAddress("127.0.0.1", port).also { socksCached = it }
}
}
override fun listenTcp(port: Int): TunneledServerSocket? {
val ln = try {
native.listenTCP(port.toLong())
} catch (e: Exception) {
throw IOException("WireGuard listenTCP $port failed: ${e.message}", e)
}
return NativeTunneledServerSocket(ln)
}
override fun localAddress(): String? = native.bindAddr().takeIf { it.isNotBlank() }
override fun close() {
try {
native.close()
} catch (_: Throwable) {
// Best-effort teardown.
}
}
companion object {
/**
* WireGuard's standard NAT/firewall keepalive interval (seconds). Injected
* into a [Peer] that omits one so the userspace tunnel stays warm.
*/
internal const val DEFAULT_KEEPALIVE_SECONDS = 25
private val SECTION_HEADER = Regex("""^\s*\[\s*(\w+)\s*]""")
private val KEEPALIVE_LINE = Regex("""^\s*PersistentKeepalive\s*=""", RegexOption.IGNORE_CASE)
/**
* Ensure every `[Peer]` in a wg-quick [configText] carries a
* `PersistentKeepalive`, injecting [seconds] into any that don't.
*
* Why: these are userspace tunnels on a roaming mobile device. When the
* underlying transport changes (Wi-Fi↔mobile, hotspot hop, app restart),
* a *cold* peer only re-homes on the next outbound data packet or after a
* handshake timeout — a multi-second window during which the carrier's WG
* address is unreachable and anything riding it (the MCP endpoint) times
* out. A keepalive makes the device re-assert its endpoint to the peer
* every [seconds], collapsing that window. An explicit user-set interval
* is left untouched. The wgbridge parser maps this line to
* `persistent_keepalive_interval` in the wireguard-go UAPI.
*/
internal fun ensurePeerKeepalive(
configText: String,
seconds: Int = DEFAULT_KEEPALIVE_SECONDS,
): String {
if (seconds <= 0) return configText
val out = StringBuilder(configText.length + 32)
val section = StringBuilder()
var sectionName: String? = null
var sectionHasKeepalive = false
fun flushSection() {
val isPeer = sectionName.equals("Peer", ignoreCase = true)
if (isPeer && !sectionHasKeepalive && section.isNotBlank()) {
out.append(section.toString().trimEnd('\n')).append('\n')
out.append("PersistentKeepalive = ").append(seconds).append('\n')
} else {
out.append(section)
}
section.setLength(0)
sectionHasKeepalive = false
}
for (line in configText.lineSequence()) {
if (SECTION_HEADER.containsMatchIn(line)) {
flushSection()
sectionName = SECTION_HEADER.find(line)!!.groupValues[1]
}
if (KEEPALIVE_LINE.containsMatchIn(line)) sectionHasKeepalive = true
section.append(line).append('\n')
}
flushSection()
return out.toString()
}
}
}
/** Wraps a native [NativeListener] as [TunneledServerSocket]. */
private class NativeTunneledServerSocket(
private val listener: NativeListener,
) : TunneledServerSocket {
override fun accept(): TunneledConnection {
val conn = try {
listener.accept()
} catch (e: Exception) {
throw IOException("WireGuard accept failed: ${e.message}", e)
}
return NativeTunneledConnection(conn)
}
override fun close() {
try {
listener.close()
} catch (_: Throwable) {
// Already-closed listeners raise here; ignore.
}
}
}
/**
* Wraps a native [NativeConn] as [TunneledConnection]. The Go side
* returns fresh byte slices from `read(size)` because gomobile copies
* `[]byte` arguments across the JNI boundary — the caller's buffer
* wouldn't be updated otherwise. The extra copy is immaterial for SSH
* traffic (small frames, network round-trip dominates).
*/
private class NativeTunneledConnection(
private val conn: NativeConn,
) : TunneledConnection {
override val remoteAddress: String?
get() = runCatching { conn.remoteAddrHost() }.getOrNull()?.takeIf { it.isNotBlank() }
override val inputStream: InputStream = object : InputStream() {
private var eof = false
override fun read(): Int {
val single = ByteArray(1)
val n = read(single, 0, 1)
return if (n == -1) -1 else single[0].toInt() and 0xFF
}
override fun read(b: ByteArray, off: Int, len: Int): Int {
if (eof) return -1
if (len == 0) return 0
val bytes = try {
conn.read(len.toLong())
} catch (_: Exception) {
eof = true
return -1
}
if (bytes == null || bytes.isEmpty()) {
eof = true
return -1
}
val n = minOf(bytes.size, len)
System.arraycopy(bytes, 0, b, off, n)
return n
}
}
override val outputStream: OutputStream = object : OutputStream() {
override fun write(b: Int) {
write(byteArrayOf((b and 0xFF).toByte()), 0, 1)
}
override fun write(b: ByteArray, off: Int, len: Int) {
val slice = if (off == 0 && len == b.size) b else b.copyOfRange(off, off + len)
try {
conn.write(slice)
} catch (e: Exception) {
throw IOException("WireGuard write failed: ${e.message}", e)
}
}
}
override fun close() {
try {
conn.close()
} catch (_: Throwable) {
// Already-closed connections raise here; ignore.
}
}
}
/**
* Wraps a native [NativeUDPConn] as [TunneledDatagramSocket]. Identical
* shape to [NativeTunneledConnection] but for UDP — gomobile returns a
* fresh `[]byte` slice per receive, so we copy into the caller's buffer
* here rather than trying to share storage across JNI.
*
* Timeouts: the Go side translates `timeoutMs <= 0` to "no deadline"
* and `timeoutMs > 0` to a one-shot read deadline. When the deadline
* fires, gomobile surfaces the underlying `net.OpError` here as a Java
* exception whose message contains "i/o timeout" — we recognise that
* and return null to match [TunneledDatagramSocket]'s timeout contract.
*/
private class NativeTunneledDatagramSocket(
private val udp: NativeUDPConn,
) : TunneledDatagramSocket {
override fun send(data: ByteArray, host: String, port: Int) {
try {
udp.writeTo(data, host, port.toLong())
} catch (e: Exception) {
throw IOException("WireGuard UDP writeTo $host:$port failed: ${e.message}", e)
}
}
override fun receive(buf: ByteArray, timeoutMs: Int): ReceivedPacket? {
val result = try {
udp.readFrom(buf.size.toLong(), timeoutMs.toLong())
} catch (e: Exception) {
if (isTimeoutException(e)) return null
throw IOException("WireGuard UDP readFrom failed: ${e.message}", e)
}
if (result == null) return null
val bytes = result.data ?: return null
val n = minOf(bytes.size, buf.size)
System.arraycopy(bytes, 0, buf, 0, n)
return ReceivedPacket(
length = n,
srcHost = result.fromHost,
srcPort = result.fromPort.toInt(),
)
}
override fun close() {
try {
udp.close()
} catch (_: Throwable) { /* idempotent */ }
}
private fun isTimeoutException(e: Throwable): Boolean {
if (e is InterruptedIOException) return true
val msg = e.message ?: return false
return msg.contains("i/o timeout", ignoreCase = true) ||
msg.contains("deadline exceeded", ignoreCase = true)
}
}
@@ -0,0 +1,89 @@
package sh.haven.core.tunnel
import org.junit.Assert.assertEquals
import org.junit.Assert.assertThrows
import org.junit.Assert.assertTrue
import org.junit.Test
class CloudflareAccessConfigBlobTest {
@Test
fun `encode-decode round-trips all fields`() {
val blob = CloudflareAccessConfigBlob(
hostname = "ssh.example.com",
teamDomain = "myteam.cloudflareaccess.com",
jwt = "eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjE3Mzc5MzQ4MDB9.sig",
jwtExpiresAt = 1737934800L,
jumpDestination = "internal-host:22",
)
val parsed = CloudflareAccessConfigBlob.parse(blob.encode())
assertEquals("ssh.example.com", parsed.hostname)
assertEquals("myteam.cloudflareaccess.com", parsed.teamDomain)
assertEquals("eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjE3Mzc5MzQ4MDB9.sig", parsed.jwt)
assertEquals(1737934800L, parsed.jwtExpiresAt)
assertEquals("internal-host:22", parsed.jumpDestination)
}
@Test
fun `missing hostname is rejected`() {
val bytes = """{"hostname":"","teamDomain":"x","jwt":"eyJ.eyJ.s"}""".toByteArray()
val ex = assertThrows(IllegalArgumentException::class.java) {
CloudflareAccessConfigBlob.parse(bytes)
}
assertTrue(ex.message!!.contains("hostname"))
}
@Test
fun `unprotected Tunnel route — missing jwt is allowed and parses cleanly`() {
// rkxspace's case (#154): Cloudflare Tunnel published-hostname
// route with no Access protection. The blob has no jwt; this
// is legal from rc4 onwards.
val bytes = """{"hostname":"ssh.example.com"}""".toByteArray()
val parsed = CloudflareAccessConfigBlob.parse(bytes)
assertEquals("ssh.example.com", parsed.hostname)
assertEquals("", parsed.jwt)
assertEquals(0L, parsed.jwtExpiresAt)
assertEquals("", parsed.jumpDestination)
}
@Test
fun `unknown json keys are ignored — newer fields don't break older clients`() {
val bytes = """{"hostname":"x","futureField":"surprise","jwt":""}""".toByteArray()
val parsed = CloudflareAccessConfigBlob.parse(bytes)
assertEquals("x", parsed.hostname)
}
@Test
fun `malformed JSON is rejected with a clear message`() {
val bytes = "{not json".toByteArray()
val ex = assertThrows(IllegalArgumentException::class.java) {
CloudflareAccessConfigBlob.parse(bytes)
}
assertTrue(ex.message!!.contains("JSON"))
}
@Test
fun `expired JWT is detected against a given now`() {
val blob = CloudflareAccessConfigBlob(
hostname = "ssh.example.com",
teamDomain = "",
jwt = "eyJ.eyJ.s",
jwtExpiresAt = 1_000L,
)
assertTrue(blob.isJwtExpired(nowEpochSeconds = 2_000L))
assertTrue(!blob.isJwtExpired(nowEpochSeconds = 500L))
}
@Test
fun `zero expiry means no expiry tracking — never reports expired`() {
// Pasted-JWT path where we couldn't parse the exp claim falls
// back to 0; the UI shouldn't show a stale-pill on those.
val blob = CloudflareAccessConfigBlob(
hostname = "ssh.example.com",
teamDomain = "",
jwt = "opaque",
jwtExpiresAt = 0L,
)
assertTrue(!blob.isJwtExpired(nowEpochSeconds = 9_999_999_999L))
}
}
@@ -0,0 +1,296 @@
package sh.haven.core.tunnel
import okhttp3.OkHttpClient
import okhttp3.WebSocket
import okhttp3.WebSocketListener
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import okio.ByteString
import org.junit.After
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertThrows
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.TimeUnit
class CloudflareAccessTunnelTest {
private lateinit var server: MockWebServer
private lateinit var client: OkHttpClient
private val openServerSockets = mutableListOf<WebSocket>()
@Before fun setUp() {
server = MockWebServer().apply { start() }
client = OkHttpClient.Builder()
.readTimeout(5, TimeUnit.SECONDS)
.build()
}
@After fun tearDown() {
// MockWebServer's shutdown waits for in-flight WS dispatchers
// to drain. Closing the server-side socket releases that thread
// so shutdown can complete.
openServerSockets.forEach { runCatching { it.close(1000, null) } }
client.dispatcher.executorService.shutdown()
client.connectionPool.evictAll()
// shutdown() throws IOException if a WS dispatcher is still draining
// when the test ends — a teardown-timing race that shows up on slow
// CI runners, not a product fault (the body assertions have already
// run). Swallow it so cleanup can't flake an otherwise-green test.
runCatching { server.shutdown() }
}
/**
* Helper: configure the next request to upgrade to a WebSocket and
* echo binary frames straight back to the client. Returns a queue
* the test can poll to inspect what bytes the server received.
*/
private fun echoOnce(): LinkedBlockingQueue<ByteString> {
val received = LinkedBlockingQueue<ByteString>()
val listener = object : WebSocketListener() {
override fun onOpen(ws: WebSocket, response: okhttp3.Response) {
synchronized(openServerSockets) { openServerSockets.add(ws) }
}
override fun onMessage(ws: WebSocket, bytes: ByteString) {
received.add(bytes)
ws.send(bytes)
}
}
server.enqueue(MockResponse().withWebSocketUpgrade(listener))
return received
}
@Test
fun `unprotected route dial sends no auth headers and uses root path`() {
// Reproduces rkxspace's setup (issue #154): a Cloudflare Tunnel
// published-hostname route with no Access in front. The client
// dials `wss://<hostname>/` with no JWT, no subprotocol, and
// standard gorilla WS headers — same as `cloudflared access ssh`.
echoOnce()
val tunnel = CloudflareAccessTunnel(
hostname = "ssh.example.com",
jwt = "",
jumpDestination = "",
httpClient = client,
gatewayUrlOverride = server.url("/").toString(),
)
val conn = tunnel.dial("ssh.example.com", 22, 3_000)
conn.close()
val req = server.takeRequest(2, TimeUnit.SECONDS)!!
assertEquals("/", req.path)
assertNull("unauth path must not send Cf-Access-Token", req.getHeader("Cf-Access-Token"))
assertNull(
"subprotocol header must not be set — cloudflared uses gorilla default",
req.getHeader("Sec-WebSocket-Protocol"),
)
// Standard WS handshake headers should be present (set by OkHttp).
assertEquals("websocket", req.getHeader("Upgrade")?.lowercase())
tunnel.close()
}
@Test
fun `Access-protected route adds Cf-Access-Token header, not a cookie`() {
// cloudflared sets Cf-Access-Token: <jwt> as an HTTP header on
// the WS upgrade (carrier/carrier.go:154). The CF_Authorization
// cookie shape is the browser path — only `Cf-Access-Token` is
// what the gateway expects from a programmatic client.
echoOnce()
val tunnel = CloudflareAccessTunnel(
hostname = "ssh.example.com",
jwt = "test-jwt-token",
jumpDestination = "",
httpClient = client,
gatewayUrlOverride = server.url("/").toString(),
)
val conn = tunnel.dial("ssh.example.com", 22, 3_000)
conn.close()
val req = server.takeRequest(2, TimeUnit.SECONDS)!!
assertEquals("test-jwt-token", req.getHeader("Cf-Access-Token"))
val cookieHeader = req.getHeader("Cookie") ?: ""
assertFalse(
"Must not send CF_Authorization cookie — gateway uses Cf-Access-Token header",
cookieHeader.contains("CF_Authorization"),
)
tunnel.close()
}
@Test
fun `bastion-mode tunnel adds Cf-Access-Jump-Destination header`() {
echoOnce()
val tunnel = CloudflareAccessTunnel(
hostname = "bastion.example.com",
jwt = "",
jumpDestination = "internal-host:22",
httpClient = client,
gatewayUrlOverride = server.url("/").toString(),
)
val conn = tunnel.dial("bastion.example.com", 22, 3_000)
conn.close()
val req = server.takeRequest(2, TimeUnit.SECONDS)!!
assertEquals("internal-host:22", req.getHeader("Cf-Access-Jump-Destination"))
tunnel.close()
}
@Test
fun `bytes round-trip through binary frames`() {
val serverInbox = echoOnce()
val tunnel = CloudflareAccessTunnel(
hostname = "ssh.example.com",
jwt = "",
jumpDestination = "",
httpClient = client,
gatewayUrlOverride = server.url("/").toString(),
)
val conn = tunnel.dial("ssh.example.com", 22, 3_000)
val payload = "SSH-2.0-OpenSSH_9.0\r\n".toByteArray()
conn.outputStream.write(payload)
conn.outputStream.flush()
val seenByServer = serverInbox.poll(2, TimeUnit.SECONDS)!!
assertArrayEquals(payload, seenByServer.toByteArray())
// Echoed back into inputStream
val readBack = ByteArray(payload.size)
var off = 0
while (off < payload.size) {
val n = conn.inputStream.read(readBack, off, payload.size - off)
check(n > 0) { "EOF before all bytes read" }
off += n
}
assertArrayEquals(payload, readBack)
conn.close()
tunnel.close()
}
@Test
fun `dial rejects hostname mismatch with a clear error`() {
val tunnel = CloudflareAccessTunnel(
hostname = "ssh.example.com",
jwt = "",
jumpDestination = "",
httpClient = client,
gatewayUrlOverride = server.url("/").toString(),
)
val ex = assertThrows(IllegalArgumentException::class.java) {
tunnel.dial("other.example.com", 22, 3_000)
}
assertTrue(ex.message!!.contains("ssh.example.com"))
assertTrue(ex.message!!.contains("other.example.com"))
tunnel.close()
}
@Test
fun `302 to Access login surfaces a sign-in hint`() {
// The signal that a Cloudflare Tunnel route is Access-protected
// is the edge replying with a 302 whose Location starts with
// /cdn-cgi/access/login (cloudflared's IsAccessResponse check).
// Surface that as actionable text rather than the generic
// "Expected HTTP 101".
server.enqueue(
MockResponse()
.setResponseCode(302)
.setHeader("Location", "https://myteam.cloudflareaccess.com/cdn-cgi/access/login/ssh.example.com?kid=abcd")
.setHeader("cf-ray", "8c34abcde1234567-LHR"),
)
val tunnel = CloudflareAccessTunnel(
hostname = "ssh.example.com",
jwt = "",
jumpDestination = "",
httpClient = client,
gatewayUrlOverride = server.url("/").toString(),
)
val ex = assertThrows(java.io.IOException::class.java) {
tunnel.dial("ssh.example.com", 22, 3_000)
}
val msg = ex.message ?: ""
assertTrue("expected sign-in hint, got: $msg", msg.contains("requires Access auth"))
assertTrue("expected hostname in message, got: $msg", msg.contains("ssh.example.com"))
assertTrue("expected cf-ray in message, got: $msg", msg.contains("8c34abcde1234567-LHR"))
tunnel.close()
}
@Test
fun `403 on upgrade surfaces JWT-rejected hint with cf-ray and body excerpt`() {
server.enqueue(
MockResponse()
.setResponseCode(403)
.setHeader("cf-ray", "8c34abcde1234567-LHR")
.setHeader("Server", "cloudflare")
.setHeader("Content-Type", "text/html; charset=UTF-8")
.setBody("<html><body>Access denied — invalid JWT</body></html>"),
)
val tunnel = CloudflareAccessTunnel(
hostname = "ssh.example.com",
jwt = "stale",
jumpDestination = "",
httpClient = client,
gatewayUrlOverride = server.url("/").toString(),
)
val ex = assertThrows(java.io.IOException::class.java) {
tunnel.dial("ssh.example.com", 22, 3_000)
}
val msg = ex.message ?: ""
assertTrue("expected JWT-invalid hint, got: $msg", msg.contains("JWT may be invalid"))
assertTrue("expected HTTP 403 in message, got: $msg", msg.contains("403"))
assertTrue("expected cf-ray in message, got: $msg", msg.contains("8c34abcde1234567-LHR"))
assertTrue(
"expected body excerpt in message, got: $msg",
msg.contains("Access denied"),
)
tunnel.close()
}
@Test
fun `5xx on upgrade surfaces gateway error message`() {
server.enqueue(
MockResponse()
.setResponseCode(502)
.setHeader("cf-ray", "abc-IAD")
.setBody("Bad Gateway"),
)
val tunnel = CloudflareAccessTunnel(
hostname = "ssh.example.com",
jwt = "",
jumpDestination = "",
httpClient = client,
gatewayUrlOverride = server.url("/").toString(),
)
val ex = assertThrows(java.io.IOException::class.java) {
tunnel.dial("ssh.example.com", 22, 3_000)
}
val msg = ex.message ?: ""
assertTrue("expected HTTP 502 in message, got: $msg", msg.contains("502"))
assertTrue("expected gateway-error phrasing, got: $msg", msg.contains("gateway error"))
assertTrue("expected cf-ray in message, got: $msg", msg.contains("abc-IAD"))
tunnel.close()
}
@Test
fun `tunnel close tears down active connections`() {
echoOnce()
val tunnel = CloudflareAccessTunnel(
hostname = "ssh.example.com",
jwt = "",
jumpDestination = "",
httpClient = client,
gatewayUrlOverride = server.url("/").toString(),
)
val conn = tunnel.dial("ssh.example.com", 22, 3_000)
tunnel.close()
// After tunnel close, writes should fail rather than silently succeed.
val writeFailed = runCatching {
conn.outputStream.write(byteArrayOf(1, 2, 3))
conn.outputStream.flush()
}.isFailure
assertTrue("write after close should fail", writeFailed)
}
}
@@ -0,0 +1,267 @@
package sh.haven.core.tunnel
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertTrue
import org.junit.Assert.fail
import org.junit.Test
import java.io.DataInputStream
import java.io.IOException
import java.net.ServerSocket
import java.net.Socket
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicReference
import kotlin.concurrent.thread
/**
* Unit tests verify the factory's *dispatch* shape — it picks the right
* java.net.Proxy.Type and surfaces an IOException for unknown types.
*
* Actual SOCKS / HTTP handshake behaviour is JDK code we don't unit-test
* here (would need a fake proxy server). Coverage at the
* Socket(Proxy)-handshake layer is the JDK's responsibility.
*/
class ProxySocketFactoryTest {
@Test
fun unknownProxyTypeThrowsOnCreateSocket() {
val factory = ProxySocketFactory("WAT", "127.0.0.1", 1080)
try {
factory.createSocket("example.com", 80)
fail("expected IOException for unknown proxy type")
} catch (_: IOException) { /* expected */ }
}
@Test
fun socks5IsAcceptedAndReturnsSocketAttempt() {
// Point at a port that won't accept — connect() will fail, but we
// verify no IOException-from-dispatch and no NPE; the factory got
// far enough to attempt the proxied connect.
val factory = ProxySocketFactory("SOCKS5", "127.0.0.1", 1, connectTimeoutMs = 100)
try {
factory.createSocket("example.com", 80)
// If it somehow returned a Socket, fine — we just verify it's
// an actual Socket.
} catch (e: IOException) {
// Connect-refused / timeout is the expected outcome here.
// We DO NOT want "Unsupported proxy type" — that'd indicate
// dispatch broke.
assertNotNull(e.message)
org.junit.Assert.assertFalse(
"must NOT report unsupported type for SOCKS5",
e.message?.contains("Unsupported proxy type") == true,
)
}
}
@Test
fun httpIsAcceptedAndReturnsSocketAttempt() {
val factory = ProxySocketFactory("HTTP", "127.0.0.1", 1, connectTimeoutMs = 100)
try {
factory.createSocket("example.com", 80)
} catch (e: IOException) {
org.junit.Assert.assertFalse(
"must NOT report unsupported type for HTTP",
e.message?.contains("Unsupported proxy type") == true,
)
}
}
@Test
fun socks4IsAcceptedSameAsSocks5() {
val factory = ProxySocketFactory("SOCKS4", "127.0.0.1", 1, connectTimeoutMs = 100)
try {
factory.createSocket("example.com", 80)
} catch (e: IOException) {
org.junit.Assert.assertFalse(
"must NOT report unsupported type for SOCKS4",
e.message?.contains("Unsupported proxy type") == true,
)
}
}
// #227: authenticated handshakes, verified against a loopback stub proxy.
@Test
fun socks5SendsRfc1929CredentialsAndDomainConnect() {
val server = ServerSocket(0, 1, java.net.InetAddress.getByName("127.0.0.1"))
val sentUser = AtomicReference<String>()
val sentPass = AtomicReference<String>()
val sentHost = AtomicReference<String>()
val sentPort = AtomicReference<Int>()
val done = CountDownLatch(1)
val srv = thread(isDaemon = true) {
server.accept().use { s ->
val ins = DataInputStream(s.getInputStream())
val out = s.getOutputStream()
// Greeting
assertEquals(0x05, ins.read())
val n = ins.read()
val methods = IntArray(n) { ins.read() }
assertTrue("client must offer user/pass auth", methods.contains(0x02))
out.write(byteArrayOf(0x05, 0x02)); out.flush() // select user/pass
// Auth (RFC 1929)
assertEquals(0x01, ins.read())
val ulen = ins.read(); val u = ByteArray(ulen).also { ins.readFully(it) }
val plen = ins.read(); val p = ByteArray(plen).also { ins.readFully(it) }
sentUser.set(String(u, Charsets.ISO_8859_1))
sentPass.set(String(p, Charsets.ISO_8859_1))
out.write(byteArrayOf(0x01, 0x00)); out.flush() // auth ok
// CONNECT
assertEquals(0x05, ins.read())
assertEquals(0x01, ins.read()) // CMD CONNECT
ins.read() // RSV
assertEquals(0x03, ins.read()) // ATYP domain (remote DNS)
val dlen = ins.read(); val d = ByteArray(dlen).also { ins.readFully(it) }
val port = (ins.read() shl 8) or ins.read()
sentHost.set(String(d, Charsets.ISO_8859_1))
sentPort.set(port)
out.write(byteArrayOf(0x05, 0x00, 0x00, 0x01, 0, 0, 0, 0, 0, 0)); out.flush()
done.countDown()
}
}
var client: Socket? = null
try {
val factory = ProxySocketFactory(
proxyType = "SOCKS5",
proxyHost = "127.0.0.1",
proxyPort = server.localPort,
connectTimeoutMs = 5_000,
proxyUser = "alice",
proxyPassword = "s3cr3t",
)
client = factory.createSocket("example.onion", 9050)
assertTrue(done.await(5, TimeUnit.SECONDS))
assertEquals("alice", sentUser.get())
assertEquals("s3cr3t", sentPass.get())
assertEquals("example.onion", sentHost.get())
assertEquals(9050, sentPort.get())
assertTrue(client.isConnected)
} finally {
client?.close(); server.close(); srv.join(2_000)
}
}
@Test
fun socks5HandlesServerChoosingNoAuth() {
val server = ServerSocket(0, 1, java.net.InetAddress.getByName("127.0.0.1"))
val sentHost = AtomicReference<String>()
val done = CountDownLatch(1)
val srv = thread(isDaemon = true) {
server.accept().use { s ->
val ins = DataInputStream(s.getInputStream())
val out = s.getOutputStream()
assertEquals(0x05, ins.read())
val n = ins.read(); repeat(n) { ins.read() }
out.write(byteArrayOf(0x05, 0x00)); out.flush() // pick no-auth
assertEquals(0x05, ins.read()); ins.read(); ins.read()
assertEquals(0x03, ins.read())
val dlen = ins.read(); val d = ByteArray(dlen).also { ins.readFully(it) }
ins.read(); ins.read() // port
sentHost.set(String(d, Charsets.ISO_8859_1))
out.write(byteArrayOf(0x05, 0x00, 0x00, 0x01, 0, 0, 0, 0, 0, 0)); out.flush()
done.countDown()
}
}
var client: Socket? = null
try {
client = ProxySocketFactory("SOCKS5", "127.0.0.1", server.localPort, 5_000, "alice", "pw")
.createSocket("host.example", 22)
assertTrue(done.await(5, TimeUnit.SECONDS))
assertEquals("host.example", sentHost.get())
assertTrue(client.isConnected)
} finally {
client?.close(); server.close(); srv.join(2_000)
}
}
@Test
fun socks5EncodesNonAsciiCredentialsByByteLength() {
// #227 regression: the RFC 1929 length octets must equal the UTF-8 BYTE
// length of the credentials, not the character count (JSch's ProxySOCKS5
// used the char count, corrupting non-ASCII creds → "server status = 01").
val server = ServerSocket(0, 1, java.net.InetAddress.getByName("127.0.0.1"))
val user = "用户" // 2 chars, 6 UTF-8 bytes
val pass = "pä55wörd" // 8 chars, 10 UTF-8 bytes (ä, ö are 2 bytes each)
val gotUser = AtomicReference<String>()
val gotPass = AtomicReference<String>()
val gotUlen = AtomicReference<Int>()
val gotPlen = AtomicReference<Int>()
val done = CountDownLatch(1)
val srv = thread(isDaemon = true) {
server.accept().use { s ->
val ins = DataInputStream(s.getInputStream())
val out = s.getOutputStream()
assertEquals(0x05, ins.read()); val n = ins.read(); repeat(n) { ins.read() }
out.write(byteArrayOf(0x05, 0x02)); out.flush()
assertEquals(0x01, ins.read())
val ulen = ins.read(); val u = ByteArray(ulen).also { ins.readFully(it) }
val plen = ins.read(); val p = ByteArray(plen).also { ins.readFully(it) }
gotUlen.set(ulen); gotPlen.set(plen)
gotUser.set(String(u, Charsets.UTF_8)); gotPass.set(String(p, Charsets.UTF_8))
out.write(byteArrayOf(0x01, 0x00)); out.flush()
assertEquals(0x05, ins.read()); ins.read(); ins.read()
assertEquals(0x03, ins.read())
val dl = ins.read(); ByteArray(dl).also { ins.readFully(it) }; ins.read(); ins.read()
out.write(byteArrayOf(0x05, 0x00, 0x00, 0x01, 0, 0, 0, 0, 0, 0)); out.flush()
done.countDown()
}
}
var client: Socket? = null
try {
client = ProxySocketFactory("SOCKS5", "127.0.0.1", server.localPort, 5_000, user, pass)
.createSocket("h", 22)
assertTrue(done.await(5, TimeUnit.SECONDS))
assertEquals("ulen must be the UTF-8 byte length, not the char count", 6, gotUlen.get())
assertEquals("plen must be the UTF-8 byte length, not the char count", 10, gotPlen.get())
assertEquals(user, gotUser.get())
assertEquals(pass, gotPass.get())
assertTrue(client.isConnected)
} finally {
client?.close(); server.close(); srv.join(2_000)
}
}
@Test
fun httpConnectSendsBasicProxyAuthorization() {
val server = ServerSocket(0, 1, java.net.InetAddress.getByName("127.0.0.1"))
val requestLines = AtomicReference<List<String>>()
val done = CountDownLatch(1)
val srv = thread(isDaemon = true) {
server.accept().use { s ->
val reader = s.getInputStream().bufferedReader(Charsets.ISO_8859_1)
val out = s.getOutputStream()
val lines = mutableListOf<String>()
while (true) {
val line = reader.readLine() ?: break
if (line.isEmpty()) break
lines.add(line)
}
requestLines.set(lines)
out.write("HTTP/1.1 200 Connection established\r\n\r\n".toByteArray(Charsets.ISO_8859_1))
out.flush()
done.countDown()
}
}
var client: Socket? = null
try {
client = ProxySocketFactory("HTTP", "127.0.0.1", server.localPort, 5_000, "alice", "pw")
.createSocket("example.com", 443)
assertTrue(done.await(5, TimeUnit.SECONDS))
val lines = requestLines.get()
assertTrue("CONNECT line present", lines.any { it == "CONNECT example.com:443 HTTP/1.1" })
val expected = "Basic " + java.util.Base64.getEncoder()
.encodeToString("alice:pw".toByteArray(Charsets.ISO_8859_1))
assertTrue(
"Proxy-Authorization header present and correct",
lines.any { it == "Proxy-Authorization: $expected" },
)
assertTrue(client.isConnected)
} finally {
client?.close(); server.close(); srv.join(2_000)
}
}
}
@@ -0,0 +1,58 @@
package sh.haven.core.tunnel
import org.junit.Assert.assertEquals
import org.junit.Test
class TailscaleConfigBlobTest {
@Test
fun `encode-decode round-trips authkey only`() {
val blob = TailscaleConfigBlob(authKey = "tskey-auth-abc123")
val parsed = TailscaleConfigBlob.parse(blob.encode())
assertEquals("tskey-auth-abc123", parsed.authKey)
assertEquals("", parsed.controlURL)
}
@Test
fun `encode-decode round-trips authkey plus headscale url`() {
val blob = TailscaleConfigBlob(
authKey = "tskey-auth-abc123",
controlURL = "https://headscale.example.com",
)
val parsed = TailscaleConfigBlob.parse(blob.encode())
assertEquals("tskey-auth-abc123", parsed.authKey)
assertEquals("https://headscale.example.com", parsed.controlURL)
}
@Test
fun `legacy raw-authkey blobs decode with empty controlURL`() {
// Pre-v5.24.86: configText was the raw authkey bytes (no JSON envelope).
// Existing users must not have to re-add their tunnels.
val legacy = "tskey-auth-legacy-format-1234".toByteArray()
val parsed = TailscaleConfigBlob.parse(legacy)
assertEquals("tskey-auth-legacy-format-1234", parsed.authKey)
assertEquals("", parsed.controlURL)
}
@Test
fun `legacy bytes that happen to start with brace fall back when JSON has no authKey`() {
// Defensive: an authkey that genuinely starts with "{" is unlikely
// (Tailscale keys are tskey-…), but a malformed/partial JSON should
// still come through as the raw payload.
val almostJson = "{not actually json}".toByteArray()
val parsed = TailscaleConfigBlob.parse(almostJson)
assertEquals("{not actually json}", parsed.authKey)
assertEquals("", parsed.controlURL)
}
@Test
fun `blank controlURL is omitted from encoded JSON`() {
val encoded = TailscaleConfigBlob(authKey = "tskey-auth-x").encode()
val text = String(encoded, Charsets.UTF_8)
// No controlUrl field at all when it's empty — keeps the blob small
// and matches the v1 default behaviour.
assert(!text.contains("controlUrl")) {
"controlUrl should not appear when blank, got: $text"
}
}
}
@@ -0,0 +1,172 @@
package sh.haven.core.tunnel
import io.mockk.coEvery
import io.mockk.mockk
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNotSame
import org.junit.Assert.assertNull
import org.junit.Assert.assertSame
import org.junit.Assert.assertTrue
import org.junit.Test
import sh.haven.core.data.db.entities.TunnelConfig
import sh.haven.core.data.db.entities.TunnelConfigType
import sh.haven.core.data.repository.TunnelConfigRepository
/**
* Unit tests for the manager's caching and refcount behaviour. Real
* tunnel creation is behind [TunnelFactory]; these tests inject a counting
* fake so they don't hit libgojni.so (not loadable in a plain JVM test).
*/
class TunnelManagerTest {
@Test
fun acquireReturnsNullWhenConfigMissing() = runTest {
val repo = mockk<TunnelConfigRepository>()
coEvery { repo.getById("missing") } returns null
val factory = CountingFactory()
val manager = TunnelManager(repo, factory)
assertNull(manager.acquire("missing", "p1"))
assertEquals(0, factory.createCount)
}
@Test
fun acquireCachesSameInstanceAcrossDependents() = runTest {
val repo = mockk<TunnelConfigRepository>()
coEvery { repo.getById("cfg-1") } returns wgConfig("cfg-1")
val factory = CountingFactory()
val manager = TunnelManager(repo, factory)
val a = manager.acquire("cfg-1", "profile-A")
val b = manager.acquire("cfg-1", "profile-B")
assertNotNull(a)
assertSame("two profiles on one config share one tunnel", a, b)
assertEquals("factory called once even with two acquirers", 1, factory.createCount)
assertEquals(2, manager.dependentCount("cfg-1"))
}
@Test
fun reAcquireSameProfileSameConfigIsIdempotent() = runTest {
val repo = mockk<TunnelConfigRepository>()
coEvery { repo.getById("cfg-1") } returns wgConfig("cfg-1")
val manager = TunnelManager(repo, CountingFactory())
manager.acquire("cfg-1", "profile-A")
manager.acquire("cfg-1", "profile-A")
assertEquals("re-acquire by same profile leaves dep count at 1", 1, manager.dependentCount("cfg-1"))
}
@Test
fun releaseWithRemainingDependentsKeepsTunnelOpen() = runTest {
val repo = mockk<TunnelConfigRepository>()
coEvery { repo.getById("cfg-1") } returns wgConfig("cfg-1")
val factory = CountingFactory()
val manager = TunnelManager(repo, factory)
val first = manager.acquire("cfg-1", "p1") as FakeTunnel
manager.acquire("cfg-1", "p2")
manager.release("p1")
assertFalse("tunnel must stay open while p2 still holds it", first.closed)
assertEquals(1, manager.dependentCount("cfg-1"))
// Re-acquire same config — still the same instance (factory not called again)
val third = manager.acquire("cfg-1", "p3")
assertSame(first, third)
assertEquals(1, factory.createCount)
}
@Test
fun releaseAfterLastDependentClosesTunnel() = runTest {
val repo = mockk<TunnelConfigRepository>()
coEvery { repo.getById("cfg-1") } returns wgConfig("cfg-1")
val factory = CountingFactory()
val manager = TunnelManager(repo, factory)
val first = manager.acquire("cfg-1", "p1") as FakeTunnel
manager.acquire("cfg-1", "p2")
manager.release("p1")
manager.release("p2")
assertTrue("last release tears down the tunnel", first.closed)
assertEquals(0, manager.dependentCount("cfg-1"))
// Re-acquire creates a fresh instance
val second = manager.acquire("cfg-1", "p3")
assertNotSame(first, second)
assertEquals(2, factory.createCount)
}
@Test
fun releaseUnknownProfileIsNoOp() = runTest {
val repo = mockk<TunnelConfigRepository>()
val factory = CountingFactory()
val manager = TunnelManager(repo, factory)
// Should not throw, should not call repo / factory
manager.release("never-acquired")
assertEquals(0, factory.createCount)
}
@Test
fun switchingConfigsAutoReleasesPrior() = runTest {
val repo = mockk<TunnelConfigRepository>()
coEvery { repo.getById("cfg-A") } returns wgConfig("cfg-A")
coEvery { repo.getById("cfg-B") } returns wgConfig("cfg-B")
val factory = CountingFactory()
val manager = TunnelManager(repo, factory)
val a = manager.acquire("cfg-A", "p1") as FakeTunnel
manager.acquire("cfg-B", "p1") // switch without explicit release
assertTrue("cfg-A torn down on auto-release", a.closed)
assertEquals(0, manager.dependentCount("cfg-A"))
assertEquals(1, manager.dependentCount("cfg-B"))
}
@Test
fun switchingConfigsKeepsPriorAliveIfOtherDependentsRemain() = runTest {
val repo = mockk<TunnelConfigRepository>()
coEvery { repo.getById("cfg-A") } returns wgConfig("cfg-A")
coEvery { repo.getById("cfg-B") } returns wgConfig("cfg-B")
val factory = CountingFactory()
val manager = TunnelManager(repo, factory)
val a = manager.acquire("cfg-A", "p1") as FakeTunnel
manager.acquire("cfg-A", "p2")
manager.acquire("cfg-B", "p1") // p1 switches, p2 still on cfg-A
assertFalse("cfg-A must stay open for p2", a.closed)
assertEquals(1, manager.dependentCount("cfg-A"))
assertEquals(1, manager.dependentCount("cfg-B"))
}
private fun wgConfig(id: String) = TunnelConfig(
id = id,
label = "test",
type = TunnelConfigType.WIREGUARD.name,
configText = "[Interface]".toByteArray(),
)
private class FakeTunnel : Tunnel {
var closed = false
override fun dial(host: String, port: Int, timeoutMs: Int): TunneledConnection =
throw UnsupportedOperationException("fake")
override fun close() { closed = true }
}
private class CountingFactory : TunnelFactory {
var createCount = 0
override fun create(config: TunnelConfig): Tunnel {
createCount++
return FakeTunnel()
}
}
}
@@ -0,0 +1,104 @@
package sh.haven.core.tunnel
import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import org.junit.Assert.assertNull
import org.junit.Assert.assertSame
import org.junit.Assert.assertThrows
import org.junit.Test
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
class TunnelProxyTest {
@Test
fun connectClampsShortTimeoutToTunnelMinimum() {
// JSch's default 10s connect timeout isn't enough for cold-peer tunnel
// handshakes (WireGuard, magicsock/DERP, MagicDNS). TunnelProxy clamps
// up to a 30s floor so those can complete. Verify the clamp is in effect
// by passing 10s in and expecting 30s to reach the tunnel.
val tunnel = mockk<Tunnel>()
val conn = fakeConn()
every { tunnel.dial("example.com", 22, 30_000) } returns conn
val proxy = TunnelProxy(tunnel)
proxy.connect(null, "example.com", 22, 10_000)
verify(exactly = 1) { tunnel.dial("example.com", 22, 30_000) }
}
@Test
fun connectPassesThroughTimeoutAboveMinimum() {
// A caller that already asks for ≥ the tunnel minimum is honoured.
val tunnel = mockk<Tunnel>()
val conn = fakeConn()
every { tunnel.dial("example.com", 22, 60_000) } returns conn
val proxy = TunnelProxy(tunnel)
proxy.connect(null, "example.com", 22, 60_000)
verify(exactly = 1) { tunnel.dial("example.com", 22, 60_000) }
}
@Test
fun streamsComeFromDialedConnection() {
val tunnel = mockk<Tunnel>()
val input = ByteArrayInputStream(byteArrayOf(1, 2, 3))
val output = ByteArrayOutputStream()
val conn = object : TunneledConnection {
override val inputStream = input
override val outputStream = output
override fun close() {}
}
every { tunnel.dial(any(), any(), any()) } returns conn
val proxy = TunnelProxy(tunnel)
proxy.connect(null, "h", 1, 0)
assertSame(input, proxy.inputStream)
assertSame(output, proxy.outputStream)
}
@Test
fun getSocketIsNull() {
// Our tunnels are userspace-netstack backed; there is no kernel
// Socket. JSch's Proxy contract allows null here, and a non-null
// return would imply direct BSD socket access we don't have.
val tunnel = mockk<Tunnel>()
every { tunnel.dial(any(), any(), any()) } returns fakeConn()
val proxy = TunnelProxy(tunnel)
proxy.connect(null, "h", 1, 0)
assertNull(proxy.socket)
}
@Test
fun closeClosesConnectionAndClearsState() {
val tunnel = mockk<Tunnel>()
val conn = mockk<TunneledConnection>(relaxed = true)
every { tunnel.dial(any(), any(), any()) } returns conn
val proxy = TunnelProxy(tunnel)
proxy.connect(null, "h", 1, 0)
proxy.close()
verify(exactly = 1) { conn.close() }
assertThrows(IllegalStateException::class.java) { proxy.inputStream }
}
@Test
fun accessingStreamsBeforeConnectFails() {
val tunnel = mockk<Tunnel>()
val proxy = TunnelProxy(tunnel)
assertThrows(IllegalStateException::class.java) { proxy.inputStream }
assertThrows(IllegalStateException::class.java) { proxy.outputStream }
}
private fun fakeConn(): TunneledConnection = object : TunneledConnection {
override val inputStream = ByteArrayInputStream(ByteArray(0))
override val outputStream = ByteArrayOutputStream()
override fun close() {}
}
}
@@ -0,0 +1,297 @@
package sh.haven.core.tunnel
import com.jcraft.jsch.ProxyHTTP
import com.jcraft.jsch.ProxySOCKS4
import com.jcraft.jsch.ProxySOCKS5
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.every
import io.mockk.mockk
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertSame
import org.junit.Assert.assertTrue
import org.junit.Test
import sh.haven.core.data.db.entities.ConnectionProfile
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.InputStream
import java.io.OutputStream
class TunnelResolverTest {
@Test
fun dialReturnsNullWhenProfileHasNoTunnelConfigId() = runTest {
val resolver = TunnelResolver(mockk(relaxed = true))
assertNull(resolver.dial(profile(tunnelConfigId = null), "h", 80, 30_000))
}
@Test
fun dialReturnsNullWhenTunnelConfigDeleted() = runTest {
val mgr = mockk<TunnelManager> {
coEvery { acquire("missing", any()) } returns null
}
val resolver = TunnelResolver(mgr)
assertNull(resolver.dial(profile(tunnelConfigId = "missing"), "h", 80, 30_000))
}
@Test
fun dialDelegatesToTunnelWhenConfigPresent() = runTest {
val conn = stubConn()
val tunnel = mockk<Tunnel> {
every { dial("example.com", 443, 5_000) } returns conn
}
val mgr = mockk<TunnelManager> {
coEvery { acquire("tid", any()) } returns tunnel
}
val resolver = TunnelResolver(mgr)
val result = resolver.dial(profile(tunnelConfigId = "tid"), "example.com", 443, 5_000)
assertSame(conn, result)
}
@Test
fun socketFactoryReturnsNullWhenNoTunnel() = runTest {
val resolver = TunnelResolver(mockk(relaxed = true))
assertNull(resolver.socketFactory(profile(tunnelConfigId = null)))
}
@Test
fun socketFactoryReturnsTunnelSocketFactoryWhenConfigPresent() = runTest {
val tunnel = mockk<Tunnel>(relaxed = true)
val mgr = mockk<TunnelManager> {
coEvery { acquire("tid", any()) } returns tunnel
}
val resolver = TunnelResolver(mgr)
val factory = resolver.socketFactory(profile(tunnelConfigId = "tid"))
assertNotNull(factory)
assertTrue(factory is TunnelSocketFactory)
}
@Test
fun socksEndpointReturnsNullWhenProfileHasNoTunnel() = runTest {
val resolver = TunnelResolver(mockk(relaxed = true))
assertNull(resolver.socksEndpoint(profile(tunnelConfigId = null)))
}
@Test
fun socksEndpointForwardsToTunnelSocksAddress() = runTest {
val expected = java.net.InetSocketAddress("127.0.0.1", 41234)
val tunnel = mockk<Tunnel> {
every { socksAddress() } returns expected
}
val mgr = mockk<TunnelManager> {
coEvery { acquire("tid", any()) } returns tunnel
}
val resolver = TunnelResolver(mgr)
val addr = resolver.socksEndpoint(profile(tunnelConfigId = "tid"))
assertSame(expected, addr)
}
@Test
fun socksEndpointReturnsNullWhenTunnelOptsOut() = runTest {
val tunnel = mockk<Tunnel> {
every { socksAddress() } returns null
}
val mgr = mockk<TunnelManager> {
coEvery { acquire("tid", any()) } returns tunnel
}
val resolver = TunnelResolver(mgr)
assertNull(resolver.socksEndpoint(profile(tunnelConfigId = "tid")))
}
@Test
fun jschProxyReturnsTunnelProxyWhenConfigPresent() = runTest {
val tunnel = mockk<Tunnel>(relaxed = true)
val mgr = mockk<TunnelManager> {
coEvery { acquire("tid", any()) } returns tunnel
}
val resolver = TunnelResolver(mgr)
val proxy = resolver.jschProxy(profile(tunnelConfigId = "tid"))
assertNotNull(proxy)
assertTrue(proxy is TunnelProxy)
}
@Test
fun jschProxyReturnsSocks5WhenSet() = runTest {
val resolver = TunnelResolver(mockk(relaxed = true))
val proxy = resolver.jschProxy(profile(proxyType = "SOCKS5", proxyHost = "127.0.0.1", proxyPort = 1080))
assertTrue(proxy is ProxySOCKS5)
}
@Test
fun jschProxyReturnsSocks4WhenSet() = runTest {
val resolver = TunnelResolver(mockk(relaxed = true))
val proxy = resolver.jschProxy(profile(proxyType = "SOCKS4", proxyHost = "127.0.0.1", proxyPort = 1080))
assertTrue(proxy is ProxySOCKS4)
}
@Test
fun jschProxyReturnsHttpWhenSet() = runTest {
val resolver = TunnelResolver(mockk(relaxed = true))
val proxy = resolver.jschProxy(profile(proxyType = "HTTP", proxyHost = "127.0.0.1", proxyPort = 8080))
assertTrue(proxy is ProxyHTTP)
}
@Test
fun jschProxyTunnelTakesPrecedenceOverSocks() = runTest {
val tunnel = mockk<Tunnel>(relaxed = true)
val mgr = mockk<TunnelManager> {
coEvery { acquire("tid", any()) } returns tunnel
}
val resolver = TunnelResolver(mgr)
val p = profile(tunnelConfigId = "tid", proxyType = "SOCKS5", proxyHost = "127.0.0.1", proxyPort = 1080)
val proxy = resolver.jschProxy(p)
assertTrue("tunnel must take precedence over legacy SOCKS proxy", proxy is TunnelProxy)
}
@Test
fun jschProxyReturnsNullForDirectProfile() = runTest {
val resolver = TunnelResolver(mockk(relaxed = true))
assertNull(resolver.jschProxy(profile()))
}
@Test
fun jschProxyReturnsNullForUnknownProxyType() = runTest {
val resolver = TunnelResolver(mockk(relaxed = true))
assertNull(resolver.jschProxy(profile(proxyType = "WAT", proxyHost = "x", proxyPort = 1)))
}
// #227: proxy auth — setUserPasswd must be applied before the JSch
// handshake, else the proxy throws JSchProxyException("…username/password
// authentication requested by server with no username/password configured").
private fun proxyField(proxy: Any, name: String): String? =
proxy.javaClass.getDeclaredField(name).apply { isAccessible = true }.get(proxy) as String?
@Test
fun jschProxySocks5WithCredsUsesAuthenticatedProxy() = runTest {
// #227: an authenticated SOCKS5 proxy must bypass JSch's ProxySOCKS5
// (whose non-ASCII RFC 1929 auth encoding is broken) and route through
// the byte-correct ProxySocketFactory via AuthenticatedProxy.
val resolver = TunnelResolver(mockk(relaxed = true))
val proxy = resolver.jschProxy(
profile(proxyType = "SOCKS5", proxyHost = "127.0.0.1", proxyPort = 1080,
proxyUser = "alice", proxyPassword = "s3cr3t"),
)
assertTrue("auth'd SOCKS5 must use AuthenticatedProxy", proxy is AuthenticatedProxy)
}
@Test
fun jschProxySocks5LeavesUserNullWhenNoCreds() = runTest {
val resolver = TunnelResolver(mockk(relaxed = true))
val proxy = resolver.jschProxy(profile(proxyType = "SOCKS5", proxyHost = "127.0.0.1", proxyPort = 1080))
assertTrue(proxy is ProxySOCKS5)
assertNull(proxyField(proxy!!, "user"))
}
@Test
fun jschProxyHttpAppliesUserPasswdWhenCredsPresent() = runTest {
val resolver = TunnelResolver(mockk(relaxed = true))
val proxy = resolver.jschProxy(
profile(proxyType = "HTTP", proxyHost = "127.0.0.1", proxyPort = 8080,
proxyUser = "bob", proxyPassword = "pw"),
)
assertTrue(proxy is ProxyHTTP)
assertEquals("bob", proxyField(proxy!!, "user"))
assertEquals("pw", proxyField(proxy, "passwd"))
}
@Test
fun jschProxySocks4AppliesUserid() = runTest {
val resolver = TunnelResolver(mockk(relaxed = true))
val proxy = resolver.jschProxy(
profile(proxyType = "SOCKS4", proxyHost = "127.0.0.1", proxyPort = 1080,
proxyUser = "carol", proxyPassword = ""),
)
assertTrue(proxy is ProxySOCKS4)
assertEquals("carol", proxyField(proxy!!, "user"))
}
@Test
fun jschProxyIgnoresBlankProxyUser() = runTest {
val resolver = TunnelResolver(mockk(relaxed = true))
val proxy = resolver.jschProxy(
profile(proxyType = "SOCKS5", proxyHost = "127.0.0.1", proxyPort = 1080,
proxyUser = "", proxyPassword = "x"),
)
assertTrue(proxy is ProxySOCKS5)
assertNull("blank username must not enable proxy auth", proxyField(proxy!!, "user"))
}
@Test
fun socketFactoryReturnsProxyFactoryWhenOnlyProxySet() = runTest {
val resolver = TunnelResolver(mockk(relaxed = true))
val factory = resolver.socketFactory(
profile(proxyType = "SOCKS5", proxyHost = "127.0.0.1", proxyPort = 1080),
)
assertNotNull(factory)
assertTrue(factory is ProxySocketFactory)
}
@Test
fun socketFactoryPrefersTunnelOverProxy() = runTest {
val tunnel = mockk<Tunnel>(relaxed = true)
val mgr = mockk<TunnelManager> {
coEvery { acquire("tid", any()) } returns tunnel
}
val resolver = TunnelResolver(mgr)
val p = profile(tunnelConfigId = "tid", proxyType = "SOCKS5", proxyHost = "127.0.0.1", proxyPort = 1080)
val factory = resolver.socketFactory(p)
assertTrue("tunnel must take precedence", factory is TunnelSocketFactory)
}
@Test
fun socketFactoryReturnsNullWhenNeitherTunnelNorProxy() = runTest {
val resolver = TunnelResolver(mockk(relaxed = true))
assertNull(resolver.socketFactory(profile()))
}
@Test
fun releaseForwardsToManager() = runTest {
val mgr = mockk<TunnelManager>(relaxed = true)
val resolver = TunnelResolver(mgr)
resolver.release("profile-A")
coVerify { mgr.release("profile-A") }
}
private fun profile(
tunnelConfigId: String? = null,
proxyType: String? = null,
proxyHost: String? = null,
proxyPort: Int = 0,
proxyUser: String? = null,
proxyPassword: String? = null,
): ConnectionProfile = ConnectionProfile(
label = "test",
host = "example.com",
username = "user",
tunnelConfigId = tunnelConfigId,
proxyType = proxyType,
proxyHost = proxyHost,
proxyPort = proxyPort,
proxyUser = proxyUser,
proxyPassword = proxyPassword,
)
private fun stubConn(): TunneledConnection = object : TunneledConnection {
override val inputStream: InputStream = ByteArrayInputStream(ByteArray(0))
override val outputStream: OutputStream = ByteArrayOutputStream()
override fun close() {}
}
}
@@ -0,0 +1,76 @@
package sh.haven.core.tunnel
import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.InputStream
import java.io.OutputStream
import java.net.InetAddress
class TunnelSocketFactoryTest {
@Test
fun createSocketDialsTunnelAndWrapsResult() {
val conn = stubConn()
val tunnel = mockk<Tunnel> {
every { dial("example.com", 443, any()) } returns conn
}
val factory = TunnelSocketFactory(tunnel)
val s = factory.createSocket("example.com", 443)
assertTrue("createSocket must return a TunneledSocket", s is TunneledSocket)
assertEquals(443, s.port)
verify { tunnel.dial("example.com", 443, 30_000) }
}
@Test
fun customTimeoutPassedThrough() {
val conn = stubConn()
val tunnel = mockk<Tunnel> {
every { dial(any(), any(), 5_000) } returns conn
}
val factory = TunnelSocketFactory(tunnel, dialTimeoutMs = 5_000)
factory.createSocket("h", 1)
verify { tunnel.dial("h", 1, 5_000) }
}
@Test
fun localBindFormDelegatesToHostPortForm() {
val conn = stubConn()
val tunnel = mockk<Tunnel> {
every { dial("h", 80, any()) } returns conn
}
val factory = TunnelSocketFactory(tunnel)
factory.createSocket("h", 80, InetAddress.getLoopbackAddress(), 12345)
verify(exactly = 1) { tunnel.dial("h", 80, 30_000) }
}
@Test
fun inetAddressFormResolvesToHostString() {
val conn = stubConn()
val tunnel = mockk<Tunnel> {
every { dial("127.0.0.1", 22, any()) } returns conn
}
val factory = TunnelSocketFactory(tunnel)
factory.createSocket(InetAddress.getByName("127.0.0.1"), 22)
verify { tunnel.dial("127.0.0.1", 22, 30_000) }
}
private fun stubConn(): TunneledConnection = object : TunneledConnection {
override val inputStream: InputStream = ByteArrayInputStream(ByteArray(0))
override val outputStream: OutputStream = ByteArrayOutputStream()
override fun close() {}
}
}
@@ -0,0 +1,114 @@
package sh.haven.core.tunnel
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertTrue
import org.junit.Assert.fail
import org.junit.Test
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.net.InetSocketAddress
class TunneledSocketTest {
@Test
fun inputStreamReadsFromConnection() {
val payload = "hello".toByteArray()
val s = TunneledSocket(FakeConn(payload), "example.com", 443)
val read = s.getInputStream().readBytes()
assertArrayEquals(payload, read)
}
@Test
fun outputStreamWritesToConnection() {
val sink = ByteArrayOutputStream()
val s = TunneledSocket(FakeConn(output = sink), "example.com", 443)
s.getOutputStream().write("world".toByteArray())
assertArrayEquals("world".toByteArray(), sink.toByteArray())
}
@Test
fun portMatchesConstructorArg() {
val s = TunneledSocket(FakeConn(), "example.com", 1234)
assertEquals(1234, s.port)
}
@Test
fun inetAddressResolvesHostname() {
val s = TunneledSocket(FakeConn(), "127.0.0.1", 80)
assertNotNull(s.inetAddress)
assertEquals("127.0.0.1", s.inetAddress?.hostAddress)
}
@Test
fun closeIsIdempotent() {
val conn = CountingConn()
val s = TunneledSocket(conn, "h", 80)
s.close()
s.close()
s.close()
assertEquals(1, conn.closeCount)
assertTrue(s.isClosed)
assertFalse(s.isConnected)
}
@Test
fun getInputStreamAfterCloseThrows() {
val s = TunneledSocket(FakeConn(), "h", 80)
s.close()
try {
s.getInputStream()
fail("expected IOException after close")
} catch (_: IOException) { /* expected */ }
}
@Test
fun getOutputStreamAfterCloseThrows() {
val s = TunneledSocket(FakeConn(), "h", 80)
s.close()
try {
s.getOutputStream()
fail("expected IOException after close")
} catch (_: IOException) { /* expected */ }
}
@Test
fun connectThrowsUnsupported() {
val s = TunneledSocket(FakeConn(), "h", 80)
try {
s.connect(InetSocketAddress("x", 1))
fail("expected UnsupportedOperationException")
} catch (_: UnsupportedOperationException) { /* expected */ }
}
@Test
fun bindThrowsUnsupported() {
val s = TunneledSocket(FakeConn(), "h", 80)
try {
s.bind(InetSocketAddress("x", 1))
fail("expected UnsupportedOperationException")
} catch (_: UnsupportedOperationException) { /* expected */ }
}
private class FakeConn(
input: ByteArray = ByteArray(0),
output: OutputStream = ByteArrayOutputStream(),
) : TunneledConnection {
override val inputStream: InputStream = ByteArrayInputStream(input)
override val outputStream: OutputStream = output
override fun close() {}
}
private class CountingConn : TunneledConnection {
override val inputStream: InputStream = ByteArrayInputStream(ByteArray(0))
override val outputStream: OutputStream = ByteArrayOutputStream()
var closeCount: Int = 0
private set
override fun close() { closeCount++ }
}
}
@@ -0,0 +1,100 @@
package sh.haven.core.tunnel
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
/** Unit tests for [WireguardTunnel.ensurePeerKeepalive]. */
class WireguardKeepaliveTest {
private fun ensure(cfg: String, seconds: Int = WireguardTunnel.DEFAULT_KEEPALIVE_SECONDS) =
WireguardTunnel.ensurePeerKeepalive(cfg, seconds)
@Test
fun `injects keepalive into a peer that lacks one`() {
val cfg = """
[Interface]
PrivateKey = abc
Address = 192.168.0.242/32
[Peer]
PublicKey = def
Endpoint = 203.0.113.5:51820
AllowedIPs = 0.0.0.0/0
""".trimIndent()
val out = ensure(cfg)
assertTrue("expected injected keepalive", out.contains("PersistentKeepalive = 25"))
// Original keys preserved.
assertTrue(out.contains("PrivateKey = abc"))
assertTrue(out.contains("Endpoint = 203.0.113.5:51820"))
assertTrue(out.contains("AllowedIPs = 0.0.0.0/0"))
// Exactly one keepalive line.
assertEquals(1, Regex("PersistentKeepalive", RegexOption.IGNORE_CASE).findAll(out).count())
}
@Test
fun `leaves an existing keepalive untouched`() {
val cfg = """
[Interface]
PrivateKey = abc
[Peer]
PublicKey = def
Endpoint = 203.0.113.5:51820
PersistentKeepalive = 15
""".trimIndent()
val out = ensure(cfg)
assertTrue("user interval kept", out.contains("PersistentKeepalive = 15"))
assertFalse("did not append the default", out.contains("PersistentKeepalive = 25"))
assertEquals(1, Regex("PersistentKeepalive", RegexOption.IGNORE_CASE).findAll(out).count())
}
@Test
fun `does not add keepalive to the interface section`() {
val cfg = "[Interface]\nPrivateKey = abc\nAddress = 10.0.0.2/32\n"
val out = ensure(cfg)
assertFalse(out.contains("PersistentKeepalive"))
}
@Test
fun `injects into each peer missing one across multiple peers`() {
val cfg = """
[Interface]
PrivateKey = abc
[Peer]
PublicKey = peer1
Endpoint = 1.1.1.1:51820
[Peer]
PublicKey = peer2
Endpoint = 2.2.2.2:51820
PersistentKeepalive = 10
""".trimIndent()
val out = ensure(cfg)
// peer1 gets the default, peer2 keeps its 10 — two keepalive lines total.
assertEquals(2, Regex("PersistentKeepalive", RegexOption.IGNORE_CASE).findAll(out).count())
assertTrue(out.contains("PersistentKeepalive = 25"))
assertTrue(out.contains("PersistentKeepalive = 10"))
// The default lands in peer1's block (before peer2's header).
val idx25 = out.indexOf("PersistentKeepalive = 25")
val idxPeer2 = out.indexOf("PublicKey = peer2")
assertTrue("default keepalive belongs to peer1", idx25 in 0 until idxPeer2)
}
@Test
fun `case-insensitive detection avoids a duplicate`() {
val cfg = "[Peer]\nPublicKey = def\npersistentkeepalive=20\n"
val out = ensure(cfg)
assertEquals(1, Regex("PersistentKeepalive", RegexOption.IGNORE_CASE).findAll(out).count())
assertTrue(out.contains("persistentkeepalive=20"))
}
@Test
fun `zero or negative interval is a no-op`() {
val cfg = "[Peer]\nPublicKey = def\nEndpoint = 1.1.1.1:51820\n"
assertEquals(cfg, ensure(cfg, seconds = 0))
assertEquals(cfg, ensure(cfg, seconds = -5))
}
}