test: cover the local network classifier and gate state machine

Extract the on-link decision into a pure function, test it with the
Android 17 SDK through Robolectric's connectivity shadows, and exercise
the gate's grant, denial, cancellation and stale-check paths with a fake
checker. The SDK 37 shadow needs jdk.internal.access exported to the
test JVM.
This commit is contained in:
austinried
2026-11-14 12:08:14 +00:00
parent 94093d5e91
commit 63c41c24b3
6 changed files with 430 additions and 31 deletions
+5
View File
@@ -91,6 +91,11 @@ android {
testOptions {
unitTests {
isIncludeAndroidResources = true
all {
// Robolectric's SDK 37 ApplicationSharedMemory reaches into jdk.internal.access via
// its FileDescriptor interceptor, which JDK 17+ does not export by default.
it.jvmArgs("--add-exports=java.base/jdk.internal.access=ALL-UNNAMED")
}
}
}
@@ -23,35 +23,24 @@ class LocalNetworkAccess(
private val deniedAddresses = mutableSetOf<String>()
suspend fun requiresPermission(address: String): Boolean {
if (Build.VERSION.SDK_INT < LOCAL_NETWORK_PERMISSION_SDK) return false
if (granted()) return false
val granted = granted()
if (Build.VERSION.SDK_INT < LOCAL_NETWORK_PERMISSION_SDK || granted) return false
val host = serverHost(address) ?: return false
return withContext(Dispatchers.IO) {
val resolved = if (isLocalHostname(host)) emptyList() else resolve(host)
val linkAddresses = currentLinkAddresses()
if (linkAddresses.isEmpty()) return@withContext false
if (isLocalHostname(host)) return@withContext true
val resolved = runCatching { InetAddress.getAllByName(host).toList() }.getOrDefault(emptyList())
if (resolved.isEmpty()) return@withContext false
val current = currentLinkAddresses()
resolved.any { candidate ->
!routedThroughVpn(candidate) && current.any { it.contains(candidate) }
}
needsPermission(
sdk = Build.VERSION.SDK_INT,
granted = granted,
host = host,
hasEligibleInterface = linkAddresses.isNotEmpty(),
resolved = resolved,
onLink = { candidate -> linkAddresses.any { it.contains(candidate) } },
vpnRouted = ::routedThroughVpn,
)
}
}
@RequiresApi(LOCAL_NETWORK_PERMISSION_SDK)
private fun routedThroughVpn(address: InetAddress): Boolean {
val manager = context.getSystemService(ConnectivityManager::class.java) ?: return false
val network = manager.activeNetwork ?: return false
val capabilities = manager.getNetworkCapabilities(network) ?: return false
if (!capabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN)) return false
return manager
.getLinkProperties(network)
?.routes
.orEmpty()
.any { route -> route.destination.contains(address) }
}
@Synchronized
fun markDenied(address: String) {
deniedAddresses += normalizeServerAddress(address)
@@ -63,6 +52,8 @@ class LocalNetworkAccess(
private fun granted(): Boolean =
ContextCompat.checkSelfPermission(context, LOCAL_NETWORK_PERMISSION) == PackageManager.PERMISSION_GRANTED
private fun resolve(host: String): List<InetAddress> = runCatching { InetAddress.getAllByName(host).toList() }.getOrDefault(emptyList())
@Suppress("DEPRECATION")
private fun currentLinkAddresses(): List<LinkAddress> {
val manager = context.getSystemService(ConnectivityManager::class.java) ?: return emptyList()
@@ -70,12 +61,31 @@ class LocalNetworkAccess(
.filter { network -> manager.getNetworkCapabilities(network)?.isLocalNetworkInterface == true }
.flatMap { network -> manager.getLinkProperties(network)?.linkAddresses.orEmpty() }
}
@RequiresApi(LOCAL_NETWORK_PERMISSION_SDK)
private fun routedThroughVpn(address: InetAddress): Boolean {
val manager = context.getSystemService(ConnectivityManager::class.java) ?: return false
val network = manager.activeNetwork ?: return false
val capabilities = manager.getNetworkCapabilities(network) ?: return false
if (!capabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN)) return false
val properties = manager.getLinkProperties(network) ?: return false
return properties.routes.any { route -> route.destination.contains(address) }
}
}
private val NetworkCapabilities.isLocalNetworkInterface: Boolean
get() =
!hasTransport(NetworkCapabilities.TRANSPORT_VPN) &&
!hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
internal fun needsPermission(
sdk: Int,
granted: Boolean,
host: String?,
hasEligibleInterface: Boolean,
resolved: List<InetAddress>,
onLink: (InetAddress) -> Boolean,
vpnRouted: (InetAddress) -> Boolean,
): Boolean {
if (sdk < LOCAL_NETWORK_PERMISSION_SDK || granted || host == null || !hasEligibleInterface) return false
if (isLocalHostname(host)) return true
return resolved.any { candidate -> !vpnRouted(candidate) && onLink(candidate) }
}
internal fun isLocalHostname(host: String): Boolean {
val normalized = host.lowercase().trimEnd('.')
@@ -84,3 +94,8 @@ internal fun isLocalHostname(host: String): Boolean {
@RequiresApi(LOCAL_NETWORK_PERMISSION_SDK)
private fun LinkAddress.contains(address: InetAddress): Boolean = IpPrefix(this.address, prefixLength).contains(address)
private val NetworkCapabilities.isLocalNetworkInterface: Boolean
get() =
!hasTransport(NetworkCapabilities.TRANSPORT_VPN) &&
!hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
@@ -33,7 +33,8 @@ import org.koin.compose.koinInject
class LocalNetworkGate internal constructor(
private val scope: CoroutineScope,
private val checker: LocalNetworkAccess,
private val requiresPermission: suspend (String) -> Boolean,
private val wasDenied: (String) -> Boolean,
private val requestPermission: (address: String, onGranted: () -> Unit, onDenied: () -> Unit) -> Unit,
private val clearPrompt: () -> Unit,
) {
@@ -57,7 +58,7 @@ class LocalNetworkGate internal constructor(
scope.launch {
val required =
try {
checker.requiresPermission(address)
requiresPermission(address)
} catch (cancellation: CancellationException) {
throw cancellation
} catch (_: Exception) {
@@ -65,7 +66,7 @@ class LocalNetworkGate internal constructor(
}
if (current != generation) return@launch
ensureActive()
if (required && !(automatic && checker.wasDenied(address))) {
if (required && !(automatic && wasDenied(address))) {
requestPermission(address, onGranted, onDenied)
} else {
onNotNeeded()
@@ -114,7 +115,8 @@ fun rememberLocalNetworkGate(): LocalNetworkGate {
remember(scope, checker) {
LocalNetworkGate(
scope = scope,
checker = checker,
requiresPermission = checker::requiresPermission,
wasDenied = checker::wasDenied,
requestPermission = { address, onGranted, onDenied ->
if (pending == null) pending = PendingRequest(address, onGranted, onDenied)
},
@@ -0,0 +1,142 @@
@file:Suppress("DEPRECATION")
package com.subtracks.data.net
import android.Manifest
import android.app.Application
import android.content.Context
import android.net.ConnectivityManager
import android.net.LinkAddress
import android.net.LinkProperties
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkInfo
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
import org.robolectric.shadows.ShadowNetwork
import org.robolectric.shadows.ShadowNetworkCapabilities
import org.robolectric.shadows.ShadowNetworkInfo
import org.robolectric.util.ReflectionHelpers
import java.net.InetAddress
@RunWith(AndroidJUnit4::class)
@Config(sdk = [37])
class LocalNetworkAccessRobolectricTest {
private val application: Application = ApplicationProvider.getApplicationContext()
@Test
fun requestsForAnAddressOnTheWifiSubnet() =
runTest {
activateWifi()
assertTrue(checker().requiresPermission("http://10.0.0.5"))
}
@Test
fun skipsAnAddressOutsideTheWifiSubnet() =
runTest {
activateWifi()
assertFalse(checker().requiresPermission("http://192.168.1.5"))
}
@Test
fun skipsWhenThePermissionIsGranted() =
runTest {
activateWifi()
shadowOf(application).grantPermissions(Manifest.permission.ACCESS_LOCAL_NETWORK)
assertFalse(checker().requiresPermission("http://10.0.0.5"))
}
@Test
fun skipsWhenTheOnlyInterfaceIsCellular() =
runTest {
activate(ConnectivityManager.TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR)
assertFalse(checker().requiresPermission("http://10.0.0.5"))
}
@Test
fun requestsForADotLocalNameWithWifi() =
runTest {
activateWifi()
assertTrue(checker().requiresPermission("http://music.local"))
}
@Test
fun skipsADotLocalNameWithoutAnEligibleInterface() =
runTest {
activate(ConnectivityManager.TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR)
assertFalse(checker().requiresPermission("http://music.local"))
}
@Test
fun requestsForALanAddressThatFallsThroughASplitTunnelVpn() =
runTest {
addWifiNetwork()
activate(ConnectivityManager.TYPE_VPN, NetworkCapabilities.TRANSPORT_VPN, address = "100.64.0.2", prefix = 32)
assertTrue(checker().requiresPermission("http://10.0.0.5"))
}
private fun activateWifi() = activate(ConnectivityManager.TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI)
private fun activate(
type: Int,
transport: Int,
address: String = "10.0.0.2",
prefix: Int = 24,
) {
shadowOf(manager()).setActiveNetworkInfo(info(type))
configure(manager().activeNetwork!!, transport, address, prefix)
}
private fun addWifiNetwork() {
val network = ShadowNetwork.newInstance(7)
shadowOf(manager()).addNetwork(network, info(ConnectivityManager.TYPE_WIFI))
configure(network, NetworkCapabilities.TRANSPORT_WIFI, "10.0.0.2", 24)
}
private fun configure(
network: Network,
transport: Int,
address: String,
prefix: Int,
) {
val capabilities = ShadowNetworkCapabilities.newInstance()
shadowOf(capabilities).addTransportType(transport)
shadowOf(manager()).setNetworkCapabilities(network, capabilities)
shadowOf(manager()).setLinkProperties(
network,
LinkProperties().apply {
setLinkAddresses(listOf(linkAddress(address, prefix)))
},
)
}
private fun linkAddress(
address: String,
prefix: Int,
): LinkAddress =
ReflectionHelpers.callConstructor(
LinkAddress::class.java,
ReflectionHelpers.ClassParameter.from(InetAddress::class.java, InetAddress.getByName(address)),
ReflectionHelpers.ClassParameter.from(Int::class.javaPrimitiveType!!, prefix),
)
private fun info(type: Int) =
ShadowNetworkInfo.newInstance(
NetworkInfo.DetailedState.CONNECTED,
type,
0,
true,
NetworkInfo.State.CONNECTED,
)
private fun checker() = LocalNetworkAccess(application)
private fun manager(): ConnectivityManager = application.getSystemService(ConnectivityManager::class.java)
}
@@ -4,6 +4,7 @@ import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import java.net.InetAddress
class LocalNetworkAccessTest {
@Test
@@ -21,4 +22,78 @@ class LocalNetworkAccessTest {
assertEquals("navidrome.example.com", serverHost("navidrome.example.com:4533"))
assertEquals("10.224.202.10", serverHost("http://10.224.202.10"))
}
@Test
fun skipsTheCheckBeforeAndroid17() {
assertFalse(check(sdk = 36))
}
@Test
fun skipsTheCheckWhenThePermissionIsGranted() {
assertFalse(check(granted = true))
}
@Test
fun skipsAHostThatCannotBeParsed() {
assertFalse(check(host = null))
}
@Test
fun skipsWhenNoEligibleInterfaceExists() {
assertFalse(check(hasEligibleInterface = false))
}
@Test
fun requestsForADotLocalNameWithAnEligibleInterface() {
assertTrue(check(host = "music.local", resolved = emptyList(), onLink = { false }))
}
@Test
fun skipsADotLocalNameWithoutAnEligibleInterface() {
assertFalse(check(host = "music.local", hasEligibleInterface = false))
}
@Test
fun requestsForAnOnLinkAddress() {
assertTrue(check(onLink = { it == address("10.0.0.5") }))
}
@Test
fun skipsAnAddressThatIsNotOnLink() {
assertFalse(check(onLink = { false }))
}
@Test
fun skipsAnAddressRoutedThroughTheVpn() {
assertFalse(check(onLink = { true }, vpnRouted = { true }))
}
@Test
fun requestsWhenAnyCandidateIsOnLinkAndNotVpnRouted() {
val onLink = address("10.0.0.5")
assertTrue(
check(
resolved = listOf(address("10.0.0.6"), onLink),
onLink = { it == onLink },
vpnRouted = { it != onLink },
),
)
}
@Test
fun skipsWhenResolutionReturnedNothing() {
assertFalse(check(resolved = emptyList()))
}
private fun check(
sdk: Int = 37,
granted: Boolean = false,
host: String? = "10.0.0.5",
hasEligibleInterface: Boolean = true,
resolved: List<InetAddress> = listOf(address("10.0.0.5")),
onLink: (InetAddress) -> Boolean = { it == address("10.0.0.5") },
vpnRouted: (InetAddress) -> Boolean = { false },
): Boolean = needsPermission(sdk, granted, host, hasEligibleInterface, resolved, onLink, vpnRouted)
private fun address(value: String): InetAddress = InetAddress.getByName(value)
}
@@ -0,0 +1,160 @@
package com.subtracks.ui.components
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.cancel
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.advanceUntilIdle
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
@OptIn(ExperimentalCoroutinesApi::class)
class LocalNetworkGateTest {
@Test
fun runsTheActionWhenThePermissionIsNotNeeded() =
runTest {
var checked = 0
val gate =
gate(requires = {
checked++
false
})
var ran = false
gate.run("http://10.0.0.5", onGranted = { ran = true })
advanceUntilIdle()
assertEquals(1, checked)
assertTrue(ran)
}
@Test
fun runsTheNotNeededCallbackForANullAddress() =
runTest {
val gate = gate(requires = { error("should not check a null address") })
var notNeeded = false
gate.run(null, onGranted = { error("should not run") }, onNotNeeded = { notNeeded = true })
advanceUntilIdle()
assertTrue(notNeeded)
}
@Test
fun runsTheActionOnGrant() =
runTest {
var requested: String? = null
val gate =
gate(
requires = { true },
request = { address, onGranted, _ ->
requested = address
onGranted()
},
)
var ran = false
gate.run("http://10.0.0.5", onGranted = { ran = true })
advanceUntilIdle()
assertEquals("http://10.0.0.5", requested)
assertTrue(ran)
}
@Test
fun runsTheDeniedCallbackOnDenial() =
runTest {
val gate = gate(requires = { true }, request = { _, _, onDenied -> onDenied() })
var denied = false
gate.run("http://10.0.0.5", onGranted = { error("should not run") }, onDenied = { denied = true })
advanceUntilIdle()
assertTrue(denied)
}
@Test
fun skipsTheAutomaticRequestForADeniedAddress() =
runTest {
var requested = false
val gate = gate(requires = { true }, denied = { true }, request = { _, _, _ -> requested = true })
var notNeeded = false
gate.run("http://10.0.0.5", onGranted = { error("should not run") }, onNotNeeded = { notNeeded = true }, automatic = true)
advanceUntilIdle()
assertFalse(requested)
assertTrue(notNeeded)
}
@Test
fun cancellingDropsTheResult() =
runTest {
val pending = CompletableDeferred<Boolean>()
var cleared = 0
val gate = gate(requires = { pending.await() }, clear = { cleared++ })
var ran = false
gate.run("http://10.0.0.5", onGranted = { ran = true })
advanceUntilIdle()
gate.cancel()
pending.complete(true)
advanceUntilIdle()
assertFalse(ran)
assertEquals(2, cleared)
}
@Test
fun ignoresAnEarlierCheckWhenANewAddressStarts() =
runTest {
val first = CompletableDeferred<Boolean>()
val second = CompletableDeferred<Boolean>()
var requested: String? = null
val gate =
gate(
requires = { address -> if (address == "http://a") first.await() else second.await() },
request = { address, onGranted, _ ->
requested = address
onGranted()
},
)
gate.run("http://a", onGranted = {})
advanceUntilIdle()
gate.run("http://b", onGranted = {})
advanceUntilIdle()
second.complete(true)
advanceUntilIdle()
first.complete(true)
advanceUntilIdle()
assertEquals("http://b", requested)
}
@Test
fun cancellingTheOwningScopeDropsTheResult() =
runTest {
val scope = CoroutineScope(StandardTestDispatcher(testScheduler))
val pending = CompletableDeferred<Boolean>()
val gate =
LocalNetworkGate(
scope = scope,
requiresPermission = { pending.await() },
wasDenied = { false },
requestPermission = { _, onGranted, _ -> onGranted() },
clearPrompt = {},
)
var ran = false
gate.run("http://10.0.0.5", onGranted = { ran = true })
advanceUntilIdle()
scope.cancel()
pending.complete(true)
advanceUntilIdle()
assertFalse(ran)
}
private fun TestScope.gate(
requires: suspend (String) -> Boolean,
denied: (String) -> Boolean = { false },
request: (String, () -> Unit, () -> Unit) -> Unit = { _, onGranted, _ -> onGranted() },
clear: () -> Unit = {},
) = LocalNetworkGate(
scope = this,
requiresPermission = requires,
wasDenied = denied,
requestPermission = request,
clearPrompt = clear,
)
}