From 0e1cede0f3f4c68d689851a2f05634e8cf93f36f Mon Sep 17 00:00:00 2001 From: austinried <4966622+austinried@users.noreply.github.com> Date: Sat, 14 Nov 2026 14:34:56 +0000 Subject: [PATCH] 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. --- .../subtracks/data/net/LocalNetworkAccess.kt | 94 ++++----- .../subtracks/data/repo/SourceRepository.kt | 4 - .../com/subtracks/data/sync/SyncManager.kt | 14 +- .../main/kotlin/com/subtracks/ui/AppRoot.kt | 59 ------ .../ui/components/LocalNetworkGate.kt | 195 ------------------ .../ui/components/LocalNetworkPermission.kt | 55 +++++ .../subtracks/ui/settings/AddSourceScreen.kt | 32 ++- .../ui/settings/AddSourceViewModel.kt | 13 +- app/src/main/res/values/strings.xml | 3 - .../net/LocalNetworkAccessRobolectricTest.kt | 73 ++++++- .../data/net/LocalNetworkAccessTest.kt | 99 --------- .../ui/components/LocalNetworkGateTest.kt | 160 -------------- 12 files changed, 185 insertions(+), 616 deletions(-) delete mode 100644 app/src/main/kotlin/com/subtracks/ui/components/LocalNetworkGate.kt create mode 100644 app/src/main/kotlin/com/subtracks/ui/components/LocalNetworkPermission.kt delete mode 100644 app/src/test/kotlin/com/subtracks/data/net/LocalNetworkAccessTest.kt delete mode 100644 app/src/test/kotlin/com/subtracks/ui/components/LocalNetworkGateTest.kt diff --git a/app/src/main/kotlin/com/subtracks/data/net/LocalNetworkAccess.kt b/app/src/main/kotlin/com/subtracks/data/net/LocalNetworkAccess.kt index 1ff4a661..45a58e1a 100644 --- a/app/src/main/kotlin/com/subtracks/data/net/LocalNetworkAccess.kt +++ b/app/src/main/kotlin/com/subtracks/data/net/LocalNetworkAccess.kt @@ -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() - + @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 = runCatching { InetAddress.getAllByName(host).toList() }.getOrDefault(emptyList()) - @Suppress("DEPRECATION") - private fun currentLinkAddresses(): List { - 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 { + 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, - 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.routesThroughVpn(address: InetAddress): Boolean = + filter { it.matches(address) } + .maxByOrNull { it.destination.prefixLength } + ?.type == RouteInfo.RTN_UNICAST + +@RequiresApi(37) +private fun List.mayFallThroughToLan(linkAddresses: List): 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) diff --git a/app/src/main/kotlin/com/subtracks/data/repo/SourceRepository.kt b/app/src/main/kotlin/com/subtracks/data/repo/SourceRepository.kt index e1bc3eef..c34cb274 100644 --- a/app/src/main/kotlin/com/subtracks/data/repo/SourceRepository.kt +++ b/app/src/main/kotlin/com/subtracks/data/repo/SourceRepository.kt @@ -71,9 +71,6 @@ class SourceRepository( private val _offline = MutableStateFlow(false) val offline: StateFlow = _offline - private val _offlineLoaded = MutableStateFlow(false) - val offlineLoaded: StateFlow = _offlineLoaded - private val _activeSource = MutableStateFlow(null) val activeSource: StateFlow = _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(), diff --git a/app/src/main/kotlin/com/subtracks/data/sync/SyncManager.kt b/app/src/main/kotlin/com/subtracks/data/sync/SyncManager.kt index 2ba3ea71..ef232f56 100644 --- a/app/src/main/kotlin/com/subtracks/data/sync/SyncManager.kt +++ b/app/src/main/kotlin/com/subtracks/data/sync/SyncManager.kt @@ -48,12 +48,6 @@ class SyncManager( private val _status = MutableStateFlow(SyncStatus.Idle) val status: StateFlow = _status - private val _runningSource = MutableStateFlow(null) - val runningSource: StateFlow = _runningSource - - private val _failedSource = MutableStateFlow(null) - val failedSource: StateFlow = _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 } diff --git a/app/src/main/kotlin/com/subtracks/ui/AppRoot.kt b/app/src/main/kotlin/com/subtracks/ui/AppRoot.kt index b1c6ad65..8270dfe7 100644 --- a/app/src/main/kotlin/com/subtracks/ui/AppRoot.kt +++ b/app/src/main/kotlin/com/subtracks/ui/AppRoot.kt @@ -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() - 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() diff --git a/app/src/main/kotlin/com/subtracks/ui/components/LocalNetworkGate.kt b/app/src/main/kotlin/com/subtracks/ui/components/LocalNetworkGate.kt deleted file mode 100644 index 13322192..00000000 --- a/app/src/main/kotlin/com/subtracks/ui/components/LocalNetworkGate.kt +++ /dev/null @@ -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() - val scope = rememberCoroutineScope() - var pending by remember { mutableStateOf(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 -} diff --git a/app/src/main/kotlin/com/subtracks/ui/components/LocalNetworkPermission.kt b/app/src/main/kotlin/com/subtracks/ui/components/LocalNetworkPermission.kt new file mode 100644 index 00000000..4b062138 --- /dev/null +++ b/app/src/main/kotlin/com/subtracks/ui/components/LocalNetworkPermission.kt @@ -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() + val preferences = koinInject() + val scope = rememberCoroutineScope() + var pending by remember { mutableStateOf(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() + } + } + } +} diff --git a/app/src/main/kotlin/com/subtracks/ui/settings/AddSourceScreen.kt b/app/src/main/kotlin/com/subtracks/ui/settings/AddSourceScreen.kt index a2e6a96f..dcc90e3d 100644 --- a/app/src/main/kotlin/com/subtracks/ui/settings/AddSourceScreen.kt +++ b/app/src/main/kotlin/com/subtracks/ui/settings/AddSourceScreen.kt @@ -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, diff --git a/app/src/main/kotlin/com/subtracks/ui/settings/AddSourceViewModel.kt b/app/src/main/kotlin/com/subtracks/ui/settings/AddSourceViewModel.kt index 3b421bf9..2f1a811d 100644 --- a/app/src/main/kotlin/com/subtracks/ui/settings/AddSourceViewModel.kt +++ b/app/src/main/kotlin/com/subtracks/ui/settings/AddSourceViewModel.kt @@ -47,10 +47,6 @@ class AddSourceViewModel( private val _state = MutableStateFlow(AddSourceState(isEditing = sourceId != null)) val state: StateFlow = _state - val offline: StateFlow = sourceRepository.offline - - val offlineLoaded: StateFlow = 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 { diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index e30146ec..0b4d0ec5 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -289,9 +289,6 @@ %1$s and its downloaded songs will be removed from this device. Connection OK Server does not support token auth; using the password instead - Allow local network access - 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. - Continue Local network access is blocked. Allow Nearby devices for Subtracks in Android settings to reach this server. Failed: %1$s Could not save: %1$s diff --git a/app/src/test/kotlin/com/subtracks/data/net/LocalNetworkAccessRobolectricTest.kt b/app/src/test/kotlin/com/subtracks/data/net/LocalNetworkAccessRobolectricTest.kt index e52f9cb4..4f8d7cc2 100644 --- a/app/src/test/kotlin/com/subtracks/data/net/LocalNetworkAccessRobolectricTest.kt +++ b/app/src/test/kotlin/com/subtracks/data/net/LocalNetworkAccessRobolectricTest.kt @@ -6,11 +6,13 @@ import android.Manifest import android.app.Application import android.content.Context import android.net.ConnectivityManager +import android.net.IpPrefix import android.net.LinkAddress import android.net.LinkProperties import android.net.Network import android.net.NetworkCapabilities import android.net.NetworkInfo +import android.net.RouteInfo import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 import kotlinx.coroutines.test.runTest @@ -31,6 +33,14 @@ import java.net.InetAddress class LocalNetworkAccessRobolectricTest { private val application: Application = ApplicationProvider.getApplicationContext() + @Test + @Config(sdk = [36]) + fun skipsBeforeAndroid17() = + runTest { + activateWifi() + assertFalse(checker().requiresPermission("http://10.0.0.5")) + } + @Test fun requestsForAnAddressOnTheWifiSubnet() = runTest { @@ -74,24 +84,70 @@ class LocalNetworkAccessRobolectricTest { assertFalse(checker().requiresPermission("http://music.local")) } + @Test + fun skipsAnAddressRoutedThroughTheVpn() = + runTest { + addWifiNetwork() + activateVpn(route("10.0.0.0", 24)) + assertFalse(checker().requiresPermission("http://10.0.0.5")) + } + @Test fun requestsForALanAddressThatFallsThroughASplitTunnelVpn() = runTest { addWifiNetwork() - activate(ConnectivityManager.TYPE_VPN, NetworkCapabilities.TRANSPORT_VPN, address = "100.64.0.2", prefix = 32) + activateVpn() assertTrue(checker().requiresPermission("http://10.0.0.5")) } + @Test + fun requestsForRoutesExcludedFromAFullTunnelVpn() = + runTest { + addWifiNetwork() + activateVpn( + route("0.0.0.0", 0), + route("10.0.0.5", 32, RouteInfo.RTN_THROW), + ) + assertTrue(checker().requiresPermission("http://10.0.0.5")) + assertTrue(checker().requiresPermission("http://music.local")) + } + + @Test + fun skipsADotLocalNameThroughAFullTunnelVpn() = + runTest { + addWifiNetwork() + activateVpn(route("0.0.0.0", 0)) + assertFalse(checker().requiresPermission("http://music.local")) + } + + @Test + fun requestsForDotLocalWhenOnlyIpv6UsesTheVpn() = + runTest { + addWifiNetwork() + activateVpn(route("::", 0)) + assertTrue(checker().requiresPermission("http://music.local")) + } + private fun activateWifi() = activate(ConnectivityManager.TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI) + private fun activateVpn(vararg routes: RouteInfo) = + activate( + ConnectivityManager.TYPE_VPN, + NetworkCapabilities.TRANSPORT_VPN, + address = "100.64.0.2", + prefix = 32, + routes = routes.toList(), + ) + private fun activate( type: Int, transport: Int, address: String = "10.0.0.2", prefix: Int = 24, + routes: List = emptyList(), ) { shadowOf(manager()).setActiveNetworkInfo(info(type)) - configure(manager().activeNetwork!!, transport, address, prefix) + configure(manager().activeNetwork!!, transport, address, prefix, routes) } private fun addWifiNetwork() { @@ -105,6 +161,7 @@ class LocalNetworkAccessRobolectricTest { transport: Int, address: String, prefix: Int, + routes: List = emptyList(), ) { val capabilities = ShadowNetworkCapabilities.newInstance() shadowOf(capabilities).addTransportType(transport) @@ -113,10 +170,22 @@ class LocalNetworkAccessRobolectricTest { network, LinkProperties().apply { setLinkAddresses(listOf(linkAddress(address, prefix))) + routes.forEach { addRoute(it) } }, ) } + private fun route( + address: String, + prefix: Int, + type: Int = RouteInfo.RTN_UNICAST, + ): RouteInfo = + ReflectionHelpers.callConstructor( + RouteInfo::class.java, + ReflectionHelpers.ClassParameter.from(IpPrefix::class.java, IpPrefix(InetAddress.getByName(address), prefix)), + ReflectionHelpers.ClassParameter.from(Int::class.javaPrimitiveType!!, type), + ) + private fun linkAddress( address: String, prefix: Int, diff --git a/app/src/test/kotlin/com/subtracks/data/net/LocalNetworkAccessTest.kt b/app/src/test/kotlin/com/subtracks/data/net/LocalNetworkAccessTest.kt deleted file mode 100644 index e563540f..00000000 --- a/app/src/test/kotlin/com/subtracks/data/net/LocalNetworkAccessTest.kt +++ /dev/null @@ -1,99 +0,0 @@ -package com.subtracks.data.net - -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 - fun treatsDotLocalHostnamesAsLocalNetwork() { - assertTrue(isLocalHostname("navidrome.local")) - assertTrue(isLocalHostname("NAVIDROME.LOCAL.")) - assertTrue(isLocalHostname("local")) - assertFalse(isLocalHostname("navidrome.example.com")) - assertFalse(isLocalHostname("local.example.com")) - } - - @Test - fun extractsTheHostFromAServerAddress() { - assertEquals("navidrome.example.com", serverHost("https://navidrome.example.com/music/")) - 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 = 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) -} diff --git a/app/src/test/kotlin/com/subtracks/ui/components/LocalNetworkGateTest.kt b/app/src/test/kotlin/com/subtracks/ui/components/LocalNetworkGateTest.kt deleted file mode 100644 index 74d584b1..00000000 --- a/app/src/test/kotlin/com/subtracks/ui/components/LocalNetworkGateTest.kt +++ /dev/null @@ -1,160 +0,0 @@ -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() - 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() - val second = CompletableDeferred() - 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() - 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, - ) -}