net: simplify local network permission to explicit server actions

Remove the automatic root prompt, network observer, denial cache, custom rationale, and source-specific sync retry state. Test and Save now validate first and launch the system Nearby devices request only when the entered destination needs it; an existing server can be recovered through Edit Server.

Keep the precise on-link check: resolve before reading the current networks, exclude cellular and VPN-routed destinations, honor longest-prefix VPN exclusions, and handle .local without attempting blocked mDNS resolution. Consolidate coverage into the SDK 37 Robolectric suite and delete the gate state-machine tests with the state machine.
This commit is contained in:
austinried
2026-11-14 14:34:56 +00:00
parent 63c41c24b3
commit 0e1cede0f3
12 changed files with 185 additions and 616 deletions
@@ -6,6 +6,7 @@ import android.net.ConnectivityManager
import android.net.IpPrefix
import android.net.LinkAddress
import android.net.NetworkCapabilities
import android.net.RouteInfo
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.core.content.ContextCompat
@@ -15,76 +16,44 @@ import java.net.InetAddress
internal const val LOCAL_NETWORK_PERMISSION = "android.permission.ACCESS_LOCAL_NETWORK"
private const val LOCAL_NETWORK_PERMISSION_SDK = 37
class LocalNetworkAccess(
private val context: Context,
) {
private val deniedAddresses = mutableSetOf<String>()
@Suppress("DEPRECATION")
suspend fun requiresPermission(address: String): Boolean {
val granted = granted()
if (Build.VERSION.SDK_INT < LOCAL_NETWORK_PERMISSION_SDK || granted) return false
if (Build.VERSION.SDK_INT < 37 || 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()
needsPermission(
sdk = Build.VERSION.SDK_INT,
granted = granted,
host = host,
hasEligibleInterface = linkAddresses.isNotEmpty(),
resolved = resolved,
onLink = { candidate -> linkAddresses.any { it.contains(candidate) } },
vpnRouted = ::routedThroughVpn,
)
val manager = context.getSystemService(ConnectivityManager::class.java) ?: return@withContext false
val linkAddresses =
manager.allNetworks
.filter { network -> manager.getNetworkCapabilities(network)?.isPhysicalLan == true }
.flatMap { network -> manager.getLinkProperties(network)?.linkAddresses.orEmpty() }
if (linkAddresses.isEmpty()) return@withContext false
val vpnRoutes = activeVpnRoutes(manager)
if (isLocalHostname(host)) {
vpnRoutes.mayFallThroughToLan(linkAddresses)
} else {
resolved.any { candidate ->
linkAddresses.any { it.contains(candidate) } && !vpnRoutes.routesThroughVpn(candidate)
}
}
}
}
@Synchronized
fun markDenied(address: String) {
deniedAddresses += normalizeServerAddress(address)
}
@Synchronized
fun wasDenied(address: String): Boolean = normalizeServerAddress(address) in deniedAddresses
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()
return manager.allNetworks
.filter { network -> manager.getNetworkCapabilities(network)?.isLocalNetworkInterface == true }
.flatMap { network -> manager.getLinkProperties(network)?.linkAddresses.orEmpty() }
private fun activeVpnRoutes(manager: ConnectivityManager): List<RouteInfo> {
val network = manager.activeNetwork ?: return emptyList()
val capabilities = manager.getNetworkCapabilities(network) ?: return emptyList()
if (!capabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN)) return emptyList()
return manager.getLinkProperties(network)?.routes.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) }
}
}
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 {
@@ -92,10 +61,23 @@ internal fun isLocalHostname(host: String): Boolean {
return normalized == "local" || normalized.endsWith(".local")
}
@RequiresApi(LOCAL_NETWORK_PERMISSION_SDK)
@RequiresApi(37)
private fun LinkAddress.contains(address: InetAddress): Boolean = IpPrefix(this.address, prefixLength).contains(address)
private val NetworkCapabilities.isLocalNetworkInterface: Boolean
@RequiresApi(37)
private fun List<RouteInfo>.routesThroughVpn(address: InetAddress): Boolean =
filter { it.matches(address) }
.maxByOrNull { it.destination.prefixLength }
?.type == RouteInfo.RTN_UNICAST
@RequiresApi(37)
private fun List<RouteInfo>.mayFallThroughToLan(linkAddresses: List<LinkAddress>): Boolean =
any { route ->
route.type != RouteInfo.RTN_UNICAST &&
linkAddresses.any { link -> route.matches(link.address) || link.contains(route.destination.address) }
} || linkAddresses.any { !routesThroughVpn(it.address) }
private val NetworkCapabilities.isPhysicalLan: Boolean
get() =
!hasTransport(NetworkCapabilities.TRANSPORT_VPN) &&
!hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
@@ -71,9 +71,6 @@ class SourceRepository(
private val _offline = MutableStateFlow(false)
val offline: StateFlow<Boolean> = _offline
private val _offlineLoaded = MutableStateFlow(false)
val offlineLoaded: StateFlow<Boolean> = _offlineLoaded
private val _activeSource = MutableStateFlow<Long?>(null)
val activeSource: StateFlow<Long?> = _activeSource
@@ -98,7 +95,6 @@ class SourceRepository(
// Read the persisted flag before the source config can build a source or probe it, so a
// cold start with offline on never touches the network.
_offline.value = prefs.offlineMode().first()
_offlineLoaded.value = true
var lastMode: NetworkMode? = null
combine(
db.sourcesDao().activeSubsonicConfig(),
@@ -48,12 +48,6 @@ class SyncManager(
private val _status = MutableStateFlow<SyncStatus>(SyncStatus.Idle)
val status: StateFlow<SyncStatus> = _status
private val _runningSource = MutableStateFlow<Long?>(null)
val runningSource: StateFlow<Long?> = _runningSource
private val _failedSource = MutableStateFlow<Long?>(null)
val failedSource: StateFlow<Long?> = _failedSource
init {
scope.launch {
for (silent in requests) {
@@ -88,11 +82,9 @@ class SyncManager(
runCatching { preferences.setLastSyncAt(System.currentTimeMillis()) }
.onFailure { Log.w("sync", "could not record the sync attempt", it) }
val startedAt = System.nanoTime()
val source = sourceRepository.activeMusicSource()
_runningSource.value = source?.id
val result =
try {
if (source == null) throw NoServerException()
val source = sourceRepository.activeMusicSource() ?: throw NoServerException()
Log.i("sync", "started (source ${source.id})")
serverActions.flush()
val resetPoint = queueRepository.captureResetPoint()
@@ -107,7 +99,6 @@ class SyncManager(
"${completed.playlists} playlists, ${completed.playlistSongs} playlist tracks, ${completed.pruned} pruned",
)
queueRepository.resetChangedOriginsAndClearPendingOrigins(changedOrigins, resetPoint, source.id)
_failedSource.value = null
SyncStatus.Success
} catch (cancellation: CancellationException) {
throw cancellation
@@ -125,10 +116,7 @@ class SyncManager(
}
}
if (!silent) showMessage(message)
_failedSource.value = source?.id
SyncStatus.Failed(message)
} finally {
_runningSource.value = null
}
_status.value = result
}
@@ -66,8 +66,6 @@ import com.subtracks.data.model.Song
import com.subtracks.data.repo.DownloadRepository
import com.subtracks.data.repo.LibraryRepository
import com.subtracks.data.repo.SourceRepository
import com.subtracks.data.sync.SyncManager
import com.subtracks.data.sync.SyncStatus
import com.subtracks.playback.PlaybackController
import com.subtracks.ui.components.AlbumInfoDialog
import com.subtracks.ui.components.ArtistChooserSheet
@@ -78,8 +76,6 @@ import com.subtracks.ui.components.LoadingState
import com.subtracks.ui.components.MenuTarget
import com.subtracks.ui.components.PlaylistInfoDialog
import com.subtracks.ui.components.SongInfoDialog
import com.subtracks.ui.components.rememberLocalNetworkGate
import com.subtracks.ui.components.rememberNetworkRevision
import com.subtracks.ui.components.statusBarScrim
import com.subtracks.ui.downloads.DownloadsRoute
import com.subtracks.ui.home.HomeListRequest
@@ -115,21 +111,6 @@ class RootViewModel(
.activeSourceId()
.map { it != null }
.stateIn(viewModelScope, SharingStarted.Eagerly, null)
val serverAddress =
sourceRepository
.activeConfig()
.map { it?.address }
.stateIn(viewModelScope, SharingStarted.Eagerly, null)
val activeSourceId =
sourceRepository
.activeSourceId()
.stateIn(viewModelScope, SharingStarted.Eagerly, null)
val offline = sourceRepository.offline
val offlineLoaded = sourceRepository.offlineLoaded
}
private const val NAVIGATION_DURATION_MS = 260
@@ -212,46 +193,6 @@ internal fun focusPops(
@Composable
fun SubtracksRoot(root: RootViewModel = koinViewModel()) {
val localNetworkGate = rememberLocalNetworkGate()
val syncManager = koinInject<SyncManager>()
val serverAddress by root.serverAddress.collectAsStateWithLifecycle()
val activeSourceId by root.activeSourceId.collectAsStateWithLifecycle()
val offline by root.offline.collectAsStateWithLifecycle()
val offlineLoaded by root.offlineLoaded.collectAsStateWithLifecycle()
val networkRevision = rememberNetworkRevision()
LaunchedEffect(serverAddress, activeSourceId, networkRevision, offline, offlineLoaded) {
if (!offlineLoaded) return@LaunchedEffect
if (offline) {
localNetworkGate.cancel()
return@LaunchedEffect
}
val promptedSourceId = activeSourceId
val statusBeforePrompt = syncManager.status.value
localNetworkGate.run(
address = serverAddress,
onGranted = {
val status = syncManager.status.value
val raced =
when (status) {
is SyncStatus.Running -> {
syncManager.runningSource.value == promptedSourceId
}
is SyncStatus.Failed -> {
statusBeforePrompt !is SyncStatus.Failed &&
syncManager.failedSource.value == promptedSourceId
}
else -> {
false
}
}
if (raced) syncManager.requestSync()
},
onNotNeeded = {},
automatic = true,
)
}
when (val hasSource = root.hasSource.collectAsStateWithLifecycle().value) {
null -> {
LoadingState()
@@ -1,195 +0,0 @@
package com.subtracks.ui.components
import android.net.ConnectivityManager
import android.net.LinkProperties
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkRequest
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.core.content.ContextCompat
import com.subtracks.R
import com.subtracks.data.net.LOCAL_NETWORK_PERMISSION
import com.subtracks.data.net.LocalNetworkAccess
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.launch
import org.koin.compose.koinInject
class LocalNetworkGate internal constructor(
private val scope: CoroutineScope,
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,
) {
private var generation = 0
private var check: Job? = null
fun run(
address: String?,
onGranted: () -> Unit,
onDenied: () -> Unit = {},
onNotNeeded: () -> Unit = onGranted,
automatic: Boolean = false,
) {
cancel()
if (address == null) {
onNotNeeded()
return
}
val current = generation
check =
scope.launch {
val required =
try {
requiresPermission(address)
} catch (cancellation: CancellationException) {
throw cancellation
} catch (_: Exception) {
false
}
if (current != generation) return@launch
ensureActive()
if (required && !(automatic && wasDenied(address))) {
requestPermission(address, onGranted, onDenied)
} else {
onNotNeeded()
}
}
}
fun cancel() {
generation++
check?.cancel()
check = null
clearPrompt()
}
}
private class PendingRequest(
val address: String,
val onGranted: () -> Unit,
val onDenied: () -> Unit,
)
@Composable
fun rememberLocalNetworkGate(): LocalNetworkGate {
val checker = koinInject<LocalNetworkAccess>()
val scope = rememberCoroutineScope()
var pending by remember { mutableStateOf<PendingRequest?>(null) }
var awaitingSystemPrompt by remember { mutableStateOf(false) }
fun deny(request: PendingRequest) {
pending = null
checker.markDenied(request.address)
request.onDenied()
}
val launcher =
rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
val request = pending
pending = null
awaitingSystemPrompt = false
if (request != null) {
if (granted) request.onGranted() else deny(request)
}
}
val gate =
remember(scope, checker) {
LocalNetworkGate(
scope = scope,
requiresPermission = checker::requiresPermission,
wasDenied = checker::wasDenied,
requestPermission = { address, onGranted, onDenied ->
if (pending == null) pending = PendingRequest(address, onGranted, onDenied)
},
clearPrompt = {
if (!awaitingSystemPrompt) pending = null
},
)
}
val request = pending
if (request != null && !awaitingSystemPrompt) {
AlertDialog(
onDismissRequest = { deny(request) },
title = { Text(stringResource(R.string.local_network_permission_title)) },
text = { Text(stringResource(R.string.local_network_permission_body)) },
confirmButton = {
TextButton(
onClick = {
awaitingSystemPrompt = true
launcher.launch(LOCAL_NETWORK_PERMISSION)
},
) {
Text(stringResource(R.string.local_network_permission_continue))
}
},
dismissButton = {
TextButton(
onClick = { deny(request) },
) {
Text(stringResource(R.string.actions_cancel))
}
},
)
}
return gate
}
@Composable
internal fun rememberNetworkRevision(): Int {
val context = LocalContext.current
var revision by remember { mutableIntStateOf(0) }
DisposableEffect(context) {
val manager = context.getSystemService(ConnectivityManager::class.java)
val mainExecutor = ContextCompat.getMainExecutor(context)
val notifyChanged = { mainExecutor.execute { revision++ } }
val callback =
object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
notifyChanged()
}
override fun onLost(network: Network) {
notifyChanged()
}
override fun onLinkPropertiesChanged(
network: Network,
linkProperties: LinkProperties,
) {
notifyChanged()
}
override fun onCapabilitiesChanged(
network: Network,
networkCapabilities: NetworkCapabilities,
) {
notifyChanged()
}
}
runCatching { manager?.registerNetworkCallback(NetworkRequest.Builder().build(), callback) }
onDispose {
if (manager != null) runCatching { manager.unregisterNetworkCallback(callback) }
}
}
return revision
}
@@ -0,0 +1,55 @@
package com.subtracks.ui.components
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import com.subtracks.data.net.LOCAL_NETWORK_PERMISSION
import com.subtracks.data.net.LocalNetworkAccess
import com.subtracks.data.prefs.UserPreferences
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import org.koin.compose.koinInject
private class PendingLocalNetworkAction(
val onGranted: () -> Unit,
val onDenied: () -> Unit,
)
@Composable
internal fun rememberLocalNetworkRequest(): (String, () -> Unit, () -> Unit) -> Unit {
val access = koinInject<LocalNetworkAccess>()
val preferences = koinInject<UserPreferences>()
val scope = rememberCoroutineScope()
var pending by remember { mutableStateOf<PendingLocalNetworkAction?>(null) }
val launcher =
rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
val action = pending
pending = null
if (granted) action?.onGranted?.invoke() else action?.onDenied?.invoke()
}
return { address, onGranted, onDenied ->
scope.launch {
val required =
try {
!preferences.offlineMode().first() && access.requiresPermission(address)
} catch (cancellation: CancellationException) {
throw cancellation
} catch (_: Exception) {
false
}
if (required) {
pending = PendingLocalNetworkAction(onGranted, onDenied)
launcher.launch(LOCAL_NETWORK_PERMISSION)
} else {
onGranted()
}
}
}
}
@@ -48,7 +48,7 @@ import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.subtracks.R
import com.subtracks.ui.components.DismissOnRequest
import com.subtracks.ui.components.rememberLocalNetworkGate
import com.subtracks.ui.components.rememberLocalNetworkRequest
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.emptyFlow
import org.koin.compose.viewmodel.koinViewModel
@@ -63,43 +63,36 @@ fun AddSourceRoute(
viewModel: AddSourceViewModel = koinViewModel(key = sourceId?.toString() ?: "new") { parametersOf(sourceId) },
) {
val state by viewModel.state.collectAsStateWithLifecycle()
val offline by viewModel.offline.collectAsStateWithLifecycle()
val offlineLoaded by viewModel.offlineLoaded.collectAsStateWithLifecycle()
val localNetworkGate = rememberLocalNetworkGate()
var gatedBusy by remember { mutableStateOf(false) }
val requestLocalNetwork = rememberLocalNetworkRequest()
var checkingNetwork by remember { mutableStateOf(false) }
fun runGated(
onGranted: () -> Unit,
onDenied: () -> Unit = onGranted,
) {
if (!offlineLoaded || gatedBusy) return
gatedBusy = true
if (checkingNetwork) return
checkingNetwork = true
val address = state.address
fun finish(action: () -> Unit) {
gatedBusy = false
checkingNetwork = false
if (viewModel.state.value.address == address) action()
}
if (offline) {
finish(onGranted)
} else {
localNetworkGate.run(
address = address,
onGranted = { finish(onGranted) },
onDenied = { finish(onDenied) },
)
}
requestLocalNetwork(address, { finish(onGranted) }, { finish(onDenied) })
}
AddSourceScreen(
state = if (gatedBusy || !offlineLoaded) state.copy(busy = true) else state,
state = if (checkingNetwork) state.copy(busy = true) else state,
onNameChange = viewModel::setName,
onAddressChange = viewModel::setAddress,
onUsernameChange = viewModel::setUsername,
onPasswordChange = viewModel::setPassword,
onTokenAuthChange = viewModel::setTokenAuth,
onTest = { runGated(viewModel::testConnection, viewModel::localNetworkPermissionDenied) },
onSave = { runGated({ viewModel.save(onSaved) }) },
onSave = {
if (viewModel.validateSave()) runGated({ viewModel.save(onSaved) })
},
onDelete = { viewModel.delete(onSaved) },
onBack = onBack,
dismissals = dismissals,
@@ -239,6 +232,7 @@ fun AddSourceScreen(
OutlinedTextField(
value = state.address,
onValueChange = onAddressChange,
enabled = !state.busy,
label = { Text(stringResource(R.string.settings_servers_fields_address)) },
placeholder = { Text(stringResource(R.string.server_address_placeholder)) },
singleLine = true,
@@ -47,10 +47,6 @@ class AddSourceViewModel(
private val _state = MutableStateFlow(AddSourceState(isEditing = sourceId != null))
val state: StateFlow<AddSourceState> = _state
val offline: StateFlow<Boolean> = sourceRepository.offline
val offlineLoaded: StateFlow<Boolean> = sourceRepository.offlineLoaded
init {
sourceId?.let { id ->
viewModelScope.launch {
@@ -122,12 +118,17 @@ class AddSourceViewModel(
}
}
fun save(onSaved: () -> Unit) {
fun validateSave(): Boolean {
val validated = _state.value.validated()
if (validated.nameError || validated.addressError) {
_state.value = validated
return
return false
}
return true
}
fun save(onSaved: () -> Unit) {
if (!validateSave()) return
_state.update { it.copy(busy = true, message = null) }
val current = _state.value
viewModelScope.launch {
-3
View File
@@ -289,9 +289,6 @@
<string name="delete_server_body">%1$s and its downloaded songs will be removed from this device.</string>
<string name="connection_ok">Connection OK</string>
<string name="connection_token_fallback">Server does not support token auth; using the password instead</string>
<string name="local_network_permission_title">Allow local network access</string>
<string name="local_network_permission_body">Android blocks apps from reaching devices on your local network until you allow it. Your server is on this network, so Subtracks needs the Nearby devices permission to sync and play. Allow it on the next prompt.</string>
<string name="local_network_permission_continue">Continue</string>
<string name="local_network_permission_denied">Local network access is blocked. Allow Nearby devices for Subtracks in Android settings to reach this server.</string>
<string name="connection_failed">Failed: %1$s</string>
<string name="save_failed">Could not save: %1$s</string>