web: allow cleartext only on the local network
- Commit
6506c56412ffecb71496ed6081453e7b3cb31e2b- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-21 05:48 UTC (3 months ago)
- Parents
635c9b2
Diff
web/src/main/AndroidManifest.xml
diff --git a/web/src/main/AndroidManifest.xml b/web/src/main/AndroidManifest.xmlindex 3a1905a157..d78f5d8028 100644--- a/web/src/main/AndroidManifest.xml+++ b/web/src/main/AndroidManifest.xml@@ -4,6 +4,9 @@ <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />+ <!-- Without this the OS blocks every socket to a private-range address, so LAN sites+ (routers, NAS, dev servers) fail to load with a generic network error. -->+ <uses-permission android:name="android.permission.ACCESS_LOCAL_NETWORK" /> <uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.RECORD_AUDIO" /> <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
web/src/main/java/com/vayunmathur/web/MainActivity.kt
diff --git a/web/src/main/java/com/vayunmathur/web/MainActivity.kt b/web/src/main/java/com/vayunmathur/web/MainActivity.ktindex 75f19d652f..0349309556 100644--- a/web/src/main/java/com/vayunmathur/web/MainActivity.kt+++ b/web/src/main/java/com/vayunmathur/web/MainActivity.kt@@ -21,6 +21,7 @@ import com.vayunmathur.library.ui.DynamicTheme import com.vayunmathur.library.util.OfflineAware import com.vayunmathur.web.data.WebRepository import com.vayunmathur.web.platform.shields.ShieldsEngine+import com.vayunmathur.web.platform.shields.ShieldsServiceWorkerClient import com.vayunmathur.web.platform.WebViewModel import com.vayunmathur.web.platform.WebViewModelFactory import kotlinx.coroutines.Dispatchers@@ -40,6 +41,8 @@ class MainActivity : ComponentActivity() { enableEdgeToEdge() // Parses ~8 MB of filter lists off the main thread. Shields fail open until it lands. lifecycleScope.launch { ShieldsEngine.load(applicationContext) }+ // Before any WebView exists: service-worker fetches bypass the WebViewClient entirely.+ ShieldsServiceWorkerClient.registerOnce(applicationContext) // Each task (window) carries its own window id + incognito flag so it keeps an independent tab set. val windowId = intent?.getStringExtra(EXTRA_WINDOW_ID) ?: WebViewModel.DEFAULT_WINDOW_ID
web/src/main/java/com/vayunmathur/web/domain/LanPolicy.kt
diff --git a/web/src/main/java/com/vayunmathur/web/domain/LanPolicy.kt b/web/src/main/java/com/vayunmathur/web/domain/LanPolicy.ktnew file mode 100644index 0000000000..2db095971a--- /dev/null+++ b/web/src/main/java/com/vayunmathur/web/domain/LanPolicy.kt@@ -0,0 +1,72 @@+package com.vayunmathur.web.domain++import java.util.concurrent.ConcurrentHashMap++/**+ * Decides whether a cleartext request is allowed, i.e. whether its host is on the LAN.+ *+ * The platform's `cleartextTrafficPermitted` flag is open so that LAN sites (routers, NAS+ * boxes, dev servers) can load at all; this is what keeps public `http://` blocked. Enforcement+ * has to live here rather than in `network_security_config.xml` because that file matches only+ * exact hostnames and a browser navigates wherever the user types.+ *+ * DNS is the rare path: `https://` skips it entirely, and IP literals, `localhost`, `*.local`+ * and dotless hosts are answered by [LocalNetwork] without a lookup. Resolution failures block,+ * which is never a regression — before this gate existed, *all* cleartext was blocked.+ *+ * Safe to call from the WebView background thread; that thread may block, which is why+ * [HostResolver] is expected to impose its own timeout.+ */+class LanPolicy(+ private val resolver: HostResolver,+ private val now: () -> Long = System::currentTimeMillis,+) {++ private class Entry(val lan: Boolean, val expiresAt: Long)++ private val cache = ConcurrentHashMap<String, Entry>()++ /** True when [url] may be fetched. Only cleartext is ever refused. */+ fun allowsCleartext(url: String): Boolean {+ if (!url.startsWith("http://", ignoreCase = true)) return true+ return isLan(LocalNetwork.hostOf(url))+ }++ fun isLan(host: String): Boolean = when (LocalNetwork.classify(host)) {+ HostKind.LAN -> true+ HostKind.PUBLIC -> false+ HostKind.NEEDS_DNS -> resolvedIsLan(host.lowercase())+ }++ fun clearCache() = cache.clear()++ /**+ * **Every** resolved address must be on the LAN. A host answering with both a private and+ * a public address is exactly the DNS-rebinding shape, so accepting any-of would be a front+ * door. An empty answer decides nothing and therefore blocks.+ */+ private fun resolvedIsLan(host: String): Boolean {+ val at = now()+ cache[host]?.let { if (it.expiresAt > at) return it.lan }++ val addresses = runCatching { resolver.resolve(host) }.getOrDefault(emptyList())+ val decided = addresses.isNotEmpty()+ val lan = decided && addresses.all {+ LocalNetwork.classify(it.substringBefore('%').lowercase()) == HostKind.LAN+ }++ // A clear-at-capacity rather than a real LRU: `android.util.LruCache` would drag a+ // platform dependency into this module and break its JVM tests.+ if (cache.size >= MAX_ENTRIES) cache.clear()+ cache[host] = Entry(lan, at + if (decided) DECIDED_TTL_MS else FAILURE_TTL_MS)+ return lan+ }++ private companion object {+ const val MAX_ENTRIES = 256+ const val DECIDED_TTL_MS = 5 * 60 * 1000L++ /** Short, so one DNS hiccup does not pin a host into "blocked" for five minutes. */+ const val FAILURE_TTL_MS = 10 * 1000L+ }+}
web/src/main/java/com/vayunmathur/web/domain/LocalNetwork.kt
diff --git a/web/src/main/java/com/vayunmathur/web/domain/LocalNetwork.kt b/web/src/main/java/com/vayunmathur/web/domain/LocalNetwork.ktnew file mode 100644index 0000000000..822c18163f--- /dev/null+++ b/web/src/main/java/com/vayunmathur/web/domain/LocalNetwork.kt@@ -0,0 +1,192 @@+package com.vayunmathur.web.domain++/** How a host relates to the local network, before any name resolution. */+enum class HostKind {+ /** Provably on the local network from the host string alone. */+ LAN,++ /** Provably not, or not in a form we are willing to interpret. */+ PUBLIC,++ /** An ordinary dotted name: only a lookup can say where it points. */+ NEEDS_DNS,+}++/** Resolves a host to its addresses. Injected so policy tests never touch the network. */+fun interface HostResolver {+ /** Textual addresses for [host], or empty when resolution fails. */+ fun resolve(host: String): List<String>+}++/**+ * Whether a host belongs to the local network, decided syntactically.+ *+ * Android's network-security-config can only match exact hostnames, so "cleartext on the+ * LAN only" cannot be expressed in XML for a browser that takes arbitrary user-typed URLs.+ * This is the classifier the app-layer gate ([LanPolicy]) is built on.+ *+ * Pure Kotlin (no `android.*`) so it runs in JVM unit tests.+ */+object LocalNetwork {++ /** Hosts that only a numeric interpretation could explain, e.g. `10.1` or `2130706433`. */+ private val NUMERIC_ONLY = Regex("^[0-9.]+$")++ /**+ * The host of [url], lowercased and without port, userinfo, brackets or IPv6 zone id.+ *+ * Tolerates scheme-less input (`nas.local`) because the omnibox hands us exactly that.+ * IPv6 brackets are consumed before the port so `[::1]:8080` yields `::1`.+ */+ fun hostOf(url: String): String {+ val afterScheme = if (url.contains("://")) url.substringAfter("://") else url+ val end = afterScheme.indexOfFirst { it == '/' || it == '?' || it == '#' }+ val authority = (if (end < 0) afterScheme else afterScheme.substring(0, end))+ .substringAfterLast('@')+ val host = if (authority.startsWith("[")) {+ val close = authority.indexOf(']')+ if (close < 0) authority.substring(1) else authority.substring(1, close)+ } else {+ authority.substringBefore(':')+ }+ val bare = host.substringBefore('%').lowercase()+ return if (bare.length > 1 && bare.endsWith('.')) bare.dropLast(1) else bare+ }++ /** Where [host] points, as far as its own text can say. */+ fun classify(host: String): HostKind {+ if (host.isEmpty()) return HostKind.PUBLIC+ if (host.contains(':')) {+ return if (parseIpv6(host)?.let(::isPrivateIpv6) == true) HostKind.LAN else HostKind.PUBLIC+ }+ parseIpv4(host)?.let { return if (isPrivateIpv4(it)) HostKind.LAN else HostKind.PUBLIC }+ // A numeric host we could not parse is one of Chromium's legacy IP spellings+ // (`10.1`, `2130706433`). Reimplementing that canonicalisation is not worth it, and+ // sending it to DNS would be pointless, so fail closed.+ if (NUMERIC_ONLY.matches(host)) return HostKind.PUBLIC+ if (isLanHostname(host)) return HostKind.LAN+ return HostKind.NEEDS_DNS+ }++ /** True for a dotted-quad or an IPv6 form; [hostOf] has already removed any port. */+ fun isIpLiteral(host: String): Boolean = host.contains(':') || parseIpv4(host) != null++ /** The no-DNS answer, for main-thread callers that must not block. */+ fun isLanHostSyntactic(host: String): Boolean = classify(host) == HostKind.LAN++ /**+ * Names that are local by definition. `.internal` is excluded because it collides with+ * real cloud-provider zones that resolve publicly.+ */+ private fun isLanHostname(host: String): Boolean =+ !host.contains('.') ||+ host == "localhost" || host.endsWith(".localhost") ||+ host == "local" || host.endsWith(".local") ||+ host == "home.arpa" || host.endsWith(".home.arpa")++ // ------------------------------------------------------------------- IPv4++ /** Strict dotted quad only. Shorthand and hex forms are rejected, so they fail closed. */+ private fun parseIpv4(host: String): IntArray? {+ val parts = host.split('.')+ if (parts.size != 4) return null+ val octets = IntArray(4)+ for (i in 0..3) {+ val part = parts[i]+ if (part.isEmpty() || part.length > 3 || !part.all { it in '0'..'9' }) return null+ val value = part.toInt()+ if (value > 255) return null+ octets[i] = value+ }+ return octets+ }++ /**+ * `100.64/10` (CGNAT) is deliberately absent: that is carrier space shared with+ * strangers, not a network the user controls.+ */+ private fun isPrivateIpv4(o: IntArray): Boolean = when {+ o[0] == 10 -> true+ o[0] == 172 && o[1] in 16..31 -> true+ o[0] == 192 && o[1] == 168 -> true+ o[0] == 169 && o[1] == 254 -> true+ o[0] == 127 -> true+ o[0] == 0 -> true+ else -> false+ }++ // ------------------------------------------------------------------- IPv6++ /** The 16 bytes of [text], or null when it is not a valid address. */+ private fun parseIpv6(text: String): ByteArray? {+ val elision = text.indexOf("::")+ if (elision >= 0 && text.indexOf("::", elision + 2) >= 0) return null++ var head = splitGroups(if (elision >= 0) text.substring(0, elision) else text) ?: return null+ var tail = splitGroups(if (elision >= 0) text.substring(elision + 2) else "") ?: return null++ // An `::ffff:a.b.c.d` tail occupies the final two hextets.+ val last = tail.lastOrNull() ?: head.lastOrNull()+ var mapped: IntArray? = null+ if (last != null && last.contains('.')) {+ mapped = parseIpv4(last) ?: return null+ if (tail.isNotEmpty()) tail = tail.dropLast(1) else head = head.dropLast(1)+ }++ val slots = if (mapped != null) 6 else 8+ if (elision >= 0) {+ if (head.size + tail.size > slots - 1) return null+ } else {+ if (head.size != slots || tail.isNotEmpty()) return null+ }++ val bytes = ByteArray(16)+ head.forEachIndexed { i, group ->+ val value = parseHextet(group) ?: return null+ bytes[i * 2] = (value shr 8).toByte()+ bytes[i * 2 + 1] = value.toByte()+ }+ tail.forEachIndexed { i, group ->+ val value = parseHextet(group) ?: return null+ val slot = slots - tail.size + i+ bytes[slot * 2] = (value shr 8).toByte()+ bytes[slot * 2 + 1] = value.toByte()+ }+ mapped?.forEachIndexed { i, octet -> bytes[12 + i] = octet.toByte() }+ return bytes+ }++ /** Colon-separated groups, or null if any is empty (which means a malformed address). */+ private fun splitGroups(text: String): List<String>? {+ if (text.isEmpty()) return emptyList()+ val groups = text.split(':')+ return if (groups.any { it.isEmpty() }) null else groups+ }++ private fun parseHextet(group: String): Int? {+ if (group.isEmpty() || group.length > 4) return null+ var value = 0+ for (c in group) {+ val digit = c.digitToIntOrNull(16) ?: return null+ value = value * 16 + digit+ }+ return value+ }++ private fun isPrivateIpv6(b: ByteArray): Boolean {+ val b0 = b[0].toInt() and 0xFF+ val b1 = b[1].toInt() and 0xFF+ // ::1+ if (b.take(15).all { it == 0.toByte() } && b[15] == 1.toByte()) return true+ // ::ffff:a.b.c.d delegates to the IPv4 rules, so the mapped form cannot smuggle+ // a private address past them (or a public one into them).+ if (b.take(10).all { it == 0.toByte() } &&+ (b[10].toInt() and 0xFF) == 0xFF && (b[11].toInt() and 0xFF) == 0xFF+ ) {+ return isPrivateIpv4(IntArray(4) { b[12 + it].toInt() and 0xFF })+ }+ if (b0 and 0xFE == 0xFC) return true // fc00::/7 unique local+ if (b0 == 0xFE && b1 and 0xC0 == 0x80) return true // fe80::/10 link local+ return false+ }+}
web/src/main/java/com/vayunmathur/web/domain/shields/UrlCleaner.kt
diff --git a/web/src/main/java/com/vayunmathur/web/domain/shields/UrlCleaner.kt b/web/src/main/java/com/vayunmathur/web/domain/shields/UrlCleaner.ktindex 0b8e6075c5..d5f29806cb 100644--- a/web/src/main/java/com/vayunmathur/web/domain/shields/UrlCleaner.kt+++ b/web/src/main/java/com/vayunmathur/web/domain/shields/UrlCleaner.kt@@ -1,5 +1,7 @@ package com.vayunmathur.web.domain.shields +import com.vayunmathur.web.domain.LocalNetwork+ /** * Brave's query-parameter stripping and HTTPS upgrading for top-level navigations. *@@ -66,28 +68,17 @@ object UrlCleaner { * The `https://` form of an `http://` [url], or null when it is already secure or is * an address HTTPS cannot serve. *- * localhost and bare IPs are left alone: they have no publicly trusted certificate and- * upgrading them breaks local development servers, which is also Brave's behaviour.+ * Bare IPs and LAN hosts are left alone: they have no publicly trusted certificate and+ * upgrading them breaks local development servers, which is also Brave's behaviour. Both+ * clauses are needed — a public bare IP like `1.2.3.4` is not LAN but still has no valid+ * cert, and `nas.local` is LAN but not an IP. */ fun httpsUpgrade(url: String): String? { if (!url.startsWith("http://", ignoreCase = true)) return null- val host = hostOf(url)- if (host.isEmpty() || host == "localhost" || host.endsWith(".localhost")) return null- if (isIpLiteral(host)) return null+ val host = LocalNetwork.hostOf(url)+ if (host.isEmpty()) return null+ if (LocalNetwork.isIpLiteral(host)) return null+ if (LocalNetwork.isLanHostSyntactic(host)) return null return "https://" + url.substring("http://".length) }-- private fun hostOf(url: String): String {- val afterScheme = url.substringAfter("://", "")- val authority = afterScheme.substringBefore('/').substringBefore('?').substringBefore('#')- return authority.substringAfter('@').substringBefore(':').lowercase()- }-- private fun isIpLiteral(host: String): Boolean {- if (host.startsWith("[")) return true // IPv6- val octets = host.split('.')- return octets.size == 4 && octets.all { part ->- part.isNotEmpty() && part.all { it.isDigit() } && part.toInt() <= 255- }- } }
web/src/main/java/com/vayunmathur/web/platform/BrowserState.kt
diff --git a/web/src/main/java/com/vayunmathur/web/platform/BrowserState.kt b/web/src/main/java/com/vayunmathur/web/platform/BrowserState.ktindex 91825a23b2..bd28809e70 100644--- a/web/src/main/java/com/vayunmathur/web/platform/BrowserState.kt+++ b/web/src/main/java/com/vayunmathur/web/platform/BrowserState.kt@@ -1,6 +1,7 @@ package com.vayunmathur.web.platform import android.net.Uri+import com.vayunmathur.web.domain.LocalNetwork import kotlinx.serialization.Serializable @Serializable@@ -53,6 +54,10 @@ enum class SitePermissionType(val key: String, val displayName: String) { } object BrowserUtils {+ // Deliberately requires a dot (or localhost, or a dotted quad): loosening this to accept+ // dotless hosts so `router` navigates would turn every one-word search - `weather`,+ // `kotlin` - into a failed navigation. `nas.local` and `192.168.1.1:8080` already match,+ // and `http://router` works through the explicit-scheme path below. private val URL_LIKE = Regex( "^(https?://)?([a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}|localhost|\\d{1,3}(\\.\\d{1,3}){3})(:\\d+)?(/.*)?$" )@@ -76,7 +81,10 @@ object BrowserUtils { if (trimmed.isEmpty()) return searchEngine.homepage if (trimmed.startsWith("http://") || trimmed.startsWith("https://")) return trimmed if (looksLikeUrl(trimmed)) {- return if (trimmed.startsWith("http")) trimmed else "https://$trimmed"+ // LAN targets are nearly all plain http and have no publicly trusted certificate,+ // so defaulting them to https would fail before the page ever loaded.+ val lan = LocalNetwork.isLanHostSyntactic(LocalNetwork.hostOf(trimmed))+ return if (lan) "http://$trimmed" else "https://$trimmed" } return searchEngine.buildQueryUrl(trimmed) }
web/src/main/java/com/vayunmathur/web/platform/PwaActivity.kt
diff --git a/web/src/main/java/com/vayunmathur/web/platform/PwaActivity.kt b/web/src/main/java/com/vayunmathur/web/platform/PwaActivity.ktindex 53dadb89ee..15330d731e 100644--- a/web/src/main/java/com/vayunmathur/web/platform/PwaActivity.kt+++ b/web/src/main/java/com/vayunmathur/web/platform/PwaActivity.kt@@ -42,11 +42,20 @@ import com.vayunmathur.library.ui.rememberMultiplePermissionRequest import com.vayunmathur.library.ui.rememberPermissionRequest import com.vayunmathur.web.platform.shields.FarblingConfig import com.vayunmathur.web.platform.shields.ShieldsEngine+import com.vayunmathur.web.platform.shields.ShieldsServiceWorkerClient import com.vayunmathur.web.platform.shields.ShieldsWebViewClient import com.vayunmathur.web.ui.applySystemDarkMode import com.vayunmathur.web.domain.EffectiveShields import com.vayunmathur.web.domain.ShieldsSettings +/**+ * A pinned installed site, running in its own task with no browser chrome.+ *+ * The cleartext gate applies here as everywhere, but there is no local-network prompt: PWAs+ * install from https origins and have no omnibox, and the permission is app-wide so granting it+ * once in the browser covers them. The seam is a PWA installed from a LAN origin — it gets+ * blocked with no in-PWA way to grant.+ */ class PwaActivity : ComponentActivity() { companion object {@@ -63,6 +72,8 @@ class PwaActivity : ComponentActivity() { // Installed sites get the same shields as the browser; loading is a no-op if the // engine is already up in this process. lifecycleScope.launch { ShieldsEngine.load(applicationContext) }+ // A pinned shortcut can be the process entry point without MainActivity ever running.+ ShieldsServiceWorkerClient.registerOnce(applicationContext) handleIntent(intent) setContent { DynamicTheme {
web/src/main/java/com/vayunmathur/web/platform/WebPermissions.kt
diff --git a/web/src/main/java/com/vayunmathur/web/platform/WebPermissions.kt b/web/src/main/java/com/vayunmathur/web/platform/WebPermissions.ktnew file mode 100644index 0000000000..ad36fee075--- /dev/null+++ b/web/src/main/java/com/vayunmathur/web/platform/WebPermissions.kt@@ -0,0 +1,19 @@+package com.vayunmathur.web.platform++import android.Manifest+import android.os.Build++/** Runtime permissions for the Web module (mirrors AndroidManifest.xml). */+object WebPermissions {+ /**+ * Local Network Protections (Android 16+). Without it the OS refuses every socket to a+ * private-range address, and unlike camera or geolocation WebView has no callback for it:+ * the connection just fails.+ *+ * `minSdk` is 31 and lint runs with `abortOnError = false`, so this SDK gate is the only+ * thing standing between us and a silent `NewApi` ship. The manifest entry itself stays+ * unguarded, per repo convention.+ */+ val LOCAL_NETWORK =+ if (Build.VERSION.SDK_INT >= 36) Manifest.permission.ACCESS_LOCAL_NETWORK else null+}
web/src/main/java/com/vayunmathur/web/platform/WebViewModel.kt
diff --git a/web/src/main/java/com/vayunmathur/web/platform/WebViewModel.kt b/web/src/main/java/com/vayunmathur/web/platform/WebViewModel.ktindex ba0d631618..7468306ce8 100644--- a/web/src/main/java/com/vayunmathur/web/platform/WebViewModel.kt+++ b/web/src/main/java/com/vayunmathur/web/platform/WebViewModel.kt@@ -4,6 +4,7 @@ package com.vayunmathur.web.platform import kotlin.uuid.Uuid import android.content.Context+import android.content.pm.PackageManager import android.net.Uri import android.util.Log import androidx.compose.runtime.getValue@@ -22,7 +23,9 @@ import com.vayunmathur.web.data.SitePermission import com.vayunmathur.web.data.WebRepository import com.vayunmathur.web.data.ShieldSetting import com.vayunmathur.web.data.StorageInfo+import androidx.core.content.ContextCompat import com.vayunmathur.web.domain.EffectiveShields+import com.vayunmathur.web.domain.LocalNetwork import com.vayunmathur.web.domain.ShieldLevel import com.vayunmathur.web.domain.ShieldsSettings import com.vayunmathur.web.platform.shields.FarblingConfig@@ -47,6 +50,7 @@ private const val P_SHIELD_TRACKERS = "web_shield_trackers" private const val P_SHIELD_COSMETIC = "web_shield_cosmetic" private const val P_SHIELD_FINGERPRINT = "web_shield_fingerprint" private const val P_SHIELD_HTTPS = "web_shield_https"+private const val P_LOCAL_NETWORK_DENIED = "web_local_network_denied" data class PermissionPrompt( val id: String = Uuid.random().toString(),@@ -73,6 +77,10 @@ class WebViewModel( companion object { const val DEFAULT_WINDOW_ID = "main"++ /** Asked at most once per process, however many windows are open. */+ @Volatile+ private var localNetworkAsked = false } // Persistence keys are namespaced per window; the default window keeps the legacy keys for back-compat.@@ -151,6 +159,13 @@ class WebViewModel( var pendingGeolocationPrompt by mutableStateOf<Triple<String, () -> Unit, () -> Unit>?>(null) private set + /** The LAN host whose page needs [WebPermissions.LOCAL_NETWORK] before it can load. */+ var pendingLocalNetworkHost by mutableStateOf<String?>(null)+ private set++ /** A previous denial, remembered across process death so we stop asking. */+ private var localNetworkDenied = false+ var pendingFileChooser by mutableStateOf<Pair<android.webkit.ValueCallback<Array<Uri>>, android.webkit.WebChromeClient.FileChooserParams>?>(null) private set @@ -180,6 +195,7 @@ class WebViewModel( val js = sp.getBoolean(P_JS_ENABLED, true) val blockThird = sp.getBoolean(P_BLOCK_THIRD_PARTY, false) val desktop = sp.getBoolean(P_DESKTOP_MODE, false)+ val lanDenied = sp.getBoolean(P_LOCAL_NETWORK_DENIED, false) val defaults = ShieldsSettings.AGGRESSIVE_DEFAULTS val savedShields = ShieldsSettings( level = sp.getString(P_SHIELD_LEVEL, null)@@ -197,6 +213,7 @@ class WebViewModel( jsEnabled = js blockThirdPartyCookies = blockThird desktopMode = desktop+ localNetworkDenied = lanDenied // Capture any tabs that were already created (e.g., from an external intent arriving before restore finishes) val preExisting = tabs.toList()@@ -461,10 +478,46 @@ class WebViewModel( fun navigateActiveTab(input: String) { val active = activeTab ?: return val dest = BrowserUtils.toNavigationUrl(input, searchEngine)+ noteNavigation(dest) onTabUrlChange(active.id, dest) omniboxFocused = false } + // ---- Local network permission ----++ /**+ * Raises [pendingLocalNetworkHost] when [url] is a LAN address we cannot reach yet.+ *+ * Called from the omnibox (so the prompt lands before the first request in the common+ * typed-URL case) and from `onPageStarted` as the catch-all, since+ * `shouldOverrideUrlLoading` never fires for a programmatic `loadUrl`, a redirect or a+ * session restore.+ *+ * Classification is syntactic only — this runs on the main thread and must never do DNS.+ */+ fun noteNavigation(url: String) {+ val permission = WebPermissions.LOCAL_NETWORK ?: return+ if (localNetworkAsked || localNetworkDenied || pendingLocalNetworkHost != null) return+ val host = LocalNetwork.hostOf(url)+ if (host.isEmpty() || !LocalNetwork.isLanHostSyntactic(host)) return+ if (ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED) return+ pendingLocalNetworkHost = host+ }++ /** Dismisses the prompt. A denial is remembered so LAN pages stop nagging. */+ fun clearLocalNetworkPrompt(denied: Boolean) {+ pendingLocalNetworkHost = null+ localNetworkAsked = true+ if (!denied) return+ localNetworkDenied = true+ viewModelScope.launch(Dispatchers.IO) {+ runCatching {+ context.getSharedPreferences("web_prefs", Context.MODE_PRIVATE)+ .edit().putBoolean(P_LOCAL_NETWORK_DENIED, true).apply()+ }.onFailure { Log.e(TAG, "persist local network denial failed", it) }+ }+ }+ fun recordHistoryVisit(url: String, title: String) { if (url.isBlank() || url == "about:blank" || url.startsWith("data:")) return if (activeTab?.isPrivate == true) return
web/src/main/java/com/vayunmathur/web/platform/shields/InetHostResolver.kt
diff --git a/web/src/main/java/com/vayunmathur/web/platform/shields/InetHostResolver.kt b/web/src/main/java/com/vayunmathur/web/platform/shields/InetHostResolver.ktnew file mode 100644index 0000000000..5eb26408c0--- /dev/null+++ b/web/src/main/java/com/vayunmathur/web/platform/shields/InetHostResolver.kt@@ -0,0 +1,34 @@+package com.vayunmathur.web.platform.shields++import com.vayunmathur.web.domain.HostResolver+import java.net.InetAddress+import java.util.concurrent.Executors+import java.util.concurrent.TimeUnit++/**+ * The production [HostResolver].+ *+ * `InetAddress.getAllByName` has no timeout, so the lookup runs on a pooled thread and is+ * abandoned after [TIMEOUT_MS]. Blocking the WebView background thread is legal; stalling it+ * for the several seconds a dead DNS server can take is not.+ */+object InetHostResolver : HostResolver {++ private const val TIMEOUT_MS = 1000L++ private val executor = Executors.newCachedThreadPool { runnable ->+ Thread(runnable, "lan-dns").apply { isDaemon = true }+ }++ override fun resolve(host: String): List<String> {+ val lookup = executor.submit<List<String>> {+ InetAddress.getAllByName(host).mapNotNull { it.hostAddress }+ }+ return try {+ lookup.get(TIMEOUT_MS, TimeUnit.MILLISECONDS)+ } catch (_: Exception) {+ lookup.cancel(true)+ emptyList()+ }+ }+}
web/src/main/java/com/vayunmathur/web/platform/shields/ShieldsRequestFilter.kt
diff --git a/web/src/main/java/com/vayunmathur/web/platform/shields/ShieldsRequestFilter.kt b/web/src/main/java/com/vayunmathur/web/platform/shields/ShieldsRequestFilter.ktnew file mode 100644index 0000000000..320d0fa2bc--- /dev/null+++ b/web/src/main/java/com/vayunmathur/web/platform/shields/ShieldsRequestFilter.kt@@ -0,0 +1,148 @@+package com.vayunmathur.web.platform.shields++import android.content.Context+import android.net.Uri+import android.text.TextUtils+import android.util.Log+import android.webkit.WebResourceRequest+import android.webkit.WebResourceResponse+import com.vayunmathur.web.R+import com.vayunmathur.web.domain.EffectiveShields+import com.vayunmathur.web.domain.LanPolicy+import com.vayunmathur.web.domain.LocalNetwork+import com.vayunmathur.web.domain.shields.ResourceTypes+import java.io.ByteArrayInputStream+import java.util.Base64++private const val TAG = "ShieldsRequestFilter"++/** Empty body for a blocked image; anything else can be zero bytes. */+private val EMPTY_GIF: ByteArray = Base64.getDecoder()+ .decode("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")++/**+ * The single gate every network request passes through.+ *+ * It lives apart from [ShieldsWebViewClient] because a `WebViewClient` is not the only caller:+ * [ShieldsServiceWorkerClient] filters service-worker fetches, which bypass the WebView client+ * entirely. Keeping one body is the same reason `WebViewBrowser` and `PwaActivity` share a+ * client — so the two cannot drift.+ */+object ShieldsRequestFilter {++ /** Process-wide, and deliberately created before any WebView exists. */+ private val lanPolicy: LanPolicy by lazy { LanPolicy(InetHostResolver) }++ /**+ * A response to serve instead of making the request, or null to let it through.+ *+ * @param pageUrl the document the request belongs to, for first/third-party detection+ */+ fun intercept(+ context: Context,+ request: WebResourceRequest,+ pageUrl: String,+ shieldsFor: (host: String) -> EffectiveShields,+ onBlocked: (pageUrl: String, blockedUrl: String) -> Unit,+ ): WebResourceResponse? {+ val url = request.url.toString()+ val scheme = request.url.scheme?.lowercase()+ if (scheme != "http" && scheme != "https") return null++ // Above the main-frame early return below, otherwise a cleartext navigation — the+ // common case — would never be gated at all.+ if (scheme == "http" && !lanPolicy.allowsCleartext(url)) {+ val host = LocalNetwork.hostOf(url)+ Log.d(TAG, "blocked public cleartext request to $host")+ return if (request.isForMainFrame) {+ blockedPageResponse(context, host)+ } else {+ emptyResponse(ResourceTypes.of(url, isMainFrame = false, headers = request.requestHeaders))+ }+ }++ if (request.isForMainFrame) return null++ val source = pageUrl.ifEmpty { url }+ val shields = shieldsFor(hostOf(source))+ if (!shields.blockTrackers) return null++ val type = ResourceTypes.of(url, isMainFrame = false, headers = request.requestHeaders)+ val result = ShieldsEngine.check(url, source, type) ?: return null+ if (!result.blocked) return null++ onBlocked(source, url)+ return result.redirect?.let { dataUrlResponse(it) } ?: emptyResponse(type)+ }++ /**+ * An empty 200 rather than a failure: a blocked script that 404s can send a page down+ * an error path, whereas an empty body usually just no-ops. The content type has to+ * match what the element expected or the browser logs a MIME error and, for images,+ * shows a broken-image placeholder.+ */+ fun emptyResponse(type: String): WebResourceResponse {+ val (mime, body) = when (type) {+ "image" -> "image/gif" to EMPTY_GIF+ "script" -> "application/javascript" to ByteArray(0)+ "stylesheet" -> "text/css" to ByteArray(0)+ "media" -> "video/mp4" to ByteArray(0)+ "xmlhttprequest" -> "application/json" to ByteArray(0)+ "subdocument" -> "text/html" to ByteArray(0)+ else -> "text/plain" to ByteArray(0)+ }+ return WebResourceResponse(mime, "utf-8", 200, "OK", emptyMap(), ByteArrayInputStream(body))+ }++ /** Serves the body of a `$redirect` rule, which the engine hands back as a data URL. */+ private fun dataUrlResponse(dataUrl: String): WebResourceResponse? = try {+ val header = dataUrl.substringBefore(',', "")+ val payload = dataUrl.substringAfter(',', "")+ val mime = header.removePrefix("data:").substringBefore(';').ifEmpty { "text/plain" }+ val bytes = if (header.endsWith(";base64")) {+ Base64.getDecoder().decode(payload)+ } else {+ Uri.decode(payload).toByteArray()+ }+ WebResourceResponse(mime, "utf-8", 200, "OK", emptyMap(), ByteArrayInputStream(bytes))+ } catch (e: Exception) {+ Log.w(TAG, "malformed redirect resource", e)+ null+ }++ /**+ * The interstitial for a blocked navigation. An empty body would render as a mystery+ * blank page, and the app has no other error-page infrastructure.+ *+ * Status **200**, not 4xx: WebView may discard the body of a non-2xx response and+ * substitute its own error page.+ */+ private fun blockedPageResponse(context: Context, host: String): WebResourceResponse {+ val title = context.getString(R.string.cleartext_blocked_title)+ // Attacker-controlled text going into a document we render.+ val message = context.getString(R.string.cleartext_blocked_message, TextUtils.htmlEncode(host))+ val html = """+ <!DOCTYPE html>+ <html><head><meta charset="utf-8">+ <meta name="viewport" content="width=device-width, initial-scale=1">+ <title>$title</title>+ <style>+ body { font-family: sans-serif; margin: 0; padding: 3rem 1.5rem;+ line-height: 1.5; background: #fdfcfb; color: #1b1b1b; }+ h1 { font-size: 1.2rem; margin: 0 0 0.75rem; }+ p { font-size: 0.95rem; margin: 0; color: #5c5c5c; }+ @media (prefers-color-scheme: dark) {+ body { background: #131314; color: #e3e3e3; }+ p { color: #a8a8a8; }+ }+ </style></head>+ <body><h1>$title</h1><p>$message</p></body></html>+ """.trimIndent()+ return WebResourceResponse(+ "text/html", "utf-8", 200, "OK", emptyMap(), ByteArrayInputStream(html.toByteArray()),+ )+ }++ private fun hostOf(url: String): String =+ runCatching { Uri.parse(url).host.orEmpty() }.getOrDefault("")+}
web/src/main/java/com/vayunmathur/web/platform/shields/ShieldsServiceWorkerClient.kt
diff --git a/web/src/main/java/com/vayunmathur/web/platform/shields/ShieldsServiceWorkerClient.kt b/web/src/main/java/com/vayunmathur/web/platform/shields/ShieldsServiceWorkerClient.ktnew file mode 100644index 0000000000..da92c3c122--- /dev/null+++ b/web/src/main/java/com/vayunmathur/web/platform/shields/ShieldsServiceWorkerClient.kt@@ -0,0 +1,66 @@+package com.vayunmathur.web.platform.shields++import android.content.Context+import android.util.Log+import android.webkit.WebResourceRequest+import android.webkit.WebResourceResponse+import androidx.webkit.ServiceWorkerClientCompat+import androidx.webkit.ServiceWorkerControllerCompat+import androidx.webkit.WebViewFeature+import com.vayunmathur.web.domain.EffectiveShields+import com.vayunmathur.web.domain.ShieldsSettings+import java.util.concurrent.atomic.AtomicBoolean++private const val TAG = "ShieldsServiceWorker"++/**+ * Applies [ShieldsRequestFilter] to service-worker fetches, which never reach a+ * `WebViewClient` and were therefore unfiltered — a page could dodge the ad-blocker, and the+ * cleartext gate, simply by registering a worker.+ *+ * The controller is process-wide and outlives every screen, so this must never capture an+ * Activity or a ViewModel.+ */+class ShieldsServiceWorkerClient(+ private val appContext: Context,+) : ServiceWorkerClientCompat() {++ override fun shouldInterceptRequest(request: WebResourceRequest): WebResourceResponse? =+ ShieldsRequestFilter.intercept(+ context = appContext,+ request = request,+ // A process-wide client has no page context. Passing the request as its own source+ // degrades first/third-party detection, but passing "" would make the engine treat+ // every worker fetch as third-party. The cleartext gate ignores source either way.+ pageUrl = request.url.toString(),+ // No panel can reach a worker, so it gets the preset the browser ships with.+ shieldsFor = { EffectiveShields.resolve(ShieldsSettings.AGGRESSIVE_DEFAULTS) },+ // The block counter is per-page and there is no page to attribute to.+ onBlocked = { _, _ -> },+ )++ companion object {+ private val registered = AtomicBoolean(false)++ /**+ * Installs the client, once per process.+ *+ * Called from both `MainActivity` and `PwaActivity`: a pinned PWA shortcut can be the+ * process entry point without `MainActivity` ever running.+ */+ fun registerOnce(context: Context) {+ if (!WebViewFeature.isFeatureSupported(WebViewFeature.SERVICE_WORKER_BASIC_USAGE)) return+ if (!WebViewFeature.isFeatureSupported(WebViewFeature.SERVICE_WORKER_SHOULD_INTERCEPT_REQUEST)) return+ if (!registered.compareAndSet(false, true)) return+ val app = context.applicationContext+ // getInstance() can throw if the WebView package is being updated underneath us.+ runCatching {+ ServiceWorkerControllerCompat.getInstance()+ .setServiceWorkerClient(ShieldsServiceWorkerClient(app))+ }.onFailure {+ registered.set(false)+ Log.w(TAG, "service worker client unavailable", it)+ }+ }+ }+}
web/src/main/java/com/vayunmathur/web/platform/shields/ShieldsWebViewClient.kt
diff --git a/web/src/main/java/com/vayunmathur/web/platform/shields/ShieldsWebViewClient.kt b/web/src/main/java/com/vayunmathur/web/platform/shields/ShieldsWebViewClient.ktindex 4a0b090add..7e8adaca68 100644--- a/web/src/main/java/com/vayunmathur/web/platform/shields/ShieldsWebViewClient.kt+++ b/web/src/main/java/com/vayunmathur/web/platform/shields/ShieldsWebViewClient.kt@@ -14,20 +14,13 @@ import androidx.webkit.WebMessageCompat import androidx.webkit.WebViewCompat import androidx.webkit.WebViewFeature import com.vayunmathur.web.domain.EffectiveShields-import com.vayunmathur.web.domain.shields.ResourceTypes import com.vayunmathur.web.domain.shields.UrlCleaner import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json-import java.io.ByteArrayInputStream-import java.util.Base64 import kotlin.random.Random private const val TAG = "ShieldsWebViewClient" -/** Empty bodies returned for blocked requests, by resource type. */-private val EMPTY_GIF: ByteArray = Base64.getDecoder()- .decode("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")- @Serializable private data class CosmeticQuery( val classes: List<String> = emptyList(),@@ -42,6 +35,9 @@ private data class CosmeticQuery( * lives here so `WebViewBrowser` and `PwaActivity` cannot drift apart. Subclasses that * override [onPageStarted] or [shouldOverrideUrlLoading] **must** call through to super. *+ * Request filtering itself is [ShieldsRequestFilter], which service workers share; this class+ * only owns the [pageUrl] a `WebResourceRequest` cannot tell us.+ * * @param shieldsFor resolved shields for a host, consulted per request * @param onBlocked called on the render thread each time a request is blocked * @param onNavigate asks the host to load a URL shields rewrote (HTTPS upgrade, param strip)@@ -94,60 +90,8 @@ open class ShieldsWebViewClient( // ---------------------------------------------------------------- network override fun shouldInterceptRequest(view: WebView, request: WebResourceRequest): WebResourceResponse? {- val url = request.url.toString()- val scheme = request.url.scheme?.lowercase()- if (scheme != "http" && scheme != "https") return null-- if (request.isForMainFrame) {- pageUrl = url- return null- }-- val source = pageUrl.ifEmpty { url }- val shields = shieldsFor(hostOf(source))- if (!shields.blockTrackers) return null-- val type = ResourceTypes.of(url, isMainFrame = false, headers = request.requestHeaders)- val result = ShieldsEngine.check(url, source, type) ?: return null- if (!result.blocked) return null-- onBlocked(source, url)- return result.redirect?.let { dataUrlResponse(it) } ?: emptyResponse(type)- }-- /**- * An empty 200 rather than a failure: a blocked script that 404s can send a page down- * an error path, whereas an empty body usually just no-ops. The content type has to- * match what the element expected or the browser logs a MIME error and, for images,- * shows a broken-image placeholder.- */- private fun emptyResponse(type: String): WebResourceResponse {- val (mime, body) = when (type) {- "image" -> "image/gif" to EMPTY_GIF- "script" -> "application/javascript" to ByteArray(0)- "stylesheet" -> "text/css" to ByteArray(0)- "media" -> "video/mp4" to ByteArray(0)- "xmlhttprequest" -> "application/json" to ByteArray(0)- "subdocument" -> "text/html" to ByteArray(0)- else -> "text/plain" to ByteArray(0)- }- return WebResourceResponse(mime, "utf-8", 200, "OK", emptyMap(), ByteArrayInputStream(body))- }-- /** Serves the body of a `$redirect` rule, which the engine hands back as a data URL. */- private fun dataUrlResponse(dataUrl: String): WebResourceResponse? = try {- val header = dataUrl.substringBefore(',', "")- val payload = dataUrl.substringAfter(',', "")- val mime = header.removePrefix("data:").substringBefore(';').ifEmpty { "text/plain" }- val bytes = if (header.endsWith(";base64")) {- Base64.getDecoder().decode(payload)- } else {- Uri.decode(payload).toByteArray()- }- WebResourceResponse(mime, "utf-8", 200, "OK", emptyMap(), ByteArrayInputStream(bytes))- } catch (e: Exception) {- Log.w(TAG, "malformed redirect resource", e)- null+ if (request.isForMainFrame) pageUrl = request.url.toString()+ return ShieldsRequestFilter.intercept(context, request, pageUrl, shieldsFor, onBlocked) } // ------------------------------------------------------------- navigation
web/src/main/java/com/vayunmathur/web/ui/BrowserPage.kt
diff --git a/web/src/main/java/com/vayunmathur/web/ui/BrowserPage.kt b/web/src/main/java/com/vayunmathur/web/ui/BrowserPage.ktindex 088e798c90..dfd4f4734e 100644--- a/web/src/main/java/com/vayunmathur/web/ui/BrowserPage.kt+++ b/web/src/main/java/com/vayunmathur/web/ui/BrowserPage.kt@@ -48,6 +48,7 @@ import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.vayunmathur.library.ui.ExternalIntents+import com.vayunmathur.library.ui.rememberPermissionRequest import com.vayunmathur.library.ui.R as UiR import com.vayunmathur.library.ui.AlertDialog import com.vayunmathur.library.ui.AppScaffold@@ -83,6 +84,7 @@ import com.vayunmathur.web.platform.shields.ShieldsWebViewClient import com.vayunmathur.web.platform.BrowserUtils import com.vayunmathur.web.platform.PwaHelper import com.vayunmathur.web.platform.PwaInfo+import com.vayunmathur.web.platform.WebPermissions import com.vayunmathur.web.platform.WebViewModel import com.vayunmathur.web.platform.isNewTab @@ -123,6 +125,14 @@ fun BrowserPage( viewModel.deliverFileChooserResult(uri?.let { arrayOf(it) }) } + // A conditional remember, but the condition is the SDK level: constant for the process.+ // Below API 36 there is no permission to ask for and the prompt never appears.+ val localNetworkRequest = WebPermissions.LOCAL_NETWORK?.let { permission ->+ rememberPermissionRequest(permission) { granted ->+ viewModel.clearLocalNetworkPrompt(denied = !granted)+ }+ }+ var showMenu by remember { mutableStateOf(false) } var showInstallDialog by remember { mutableStateOf(false) } var linkContextMenuUrl by remember { mutableStateOf<String?>(null) }@@ -478,6 +488,17 @@ fun BrowserPage( ) } + viewModel.pendingLocalNetworkHost?.let { host ->+ LocalNetworkPromptSheet(+ host = host,+ // Tap-gated: rememberPermissionRequest opens system settings on a+ // denial-without-rationale, so launching this automatically would eject a+ // permanently-denied user out of the app on every LAN page load.+ onAllow = { localNetworkRequest?.invoke() },+ onDeny = { viewModel.clearLocalNetworkPrompt(denied = true) },+ )+ }+ viewModel.pendingFileChooser?.let { (_, params) -> val mimeTypes = try { params.acceptTypes.toList() } catch (_: Exception) { emptyList() } val allowMultiple = try { params.mode == android.webkit.WebChromeClient.FileChooserParams.MODE_OPEN_MULTIPLE } catch (_: Exception) { false }
web/src/main/java/com/vayunmathur/web/ui/PermissionSheets.kt
diff --git a/web/src/main/java/com/vayunmathur/web/ui/PermissionSheets.kt b/web/src/main/java/com/vayunmathur/web/ui/PermissionSheets.ktindex de69f32cf4..bd82085445 100644--- a/web/src/main/java/com/vayunmathur/web/ui/PermissionSheets.kt+++ b/web/src/main/java/com/vayunmathur/web/ui/PermissionSheets.kt@@ -109,6 +109,21 @@ internal fun GeolocationPromptSheet( ) } +@Composable+internal fun LocalNetworkPromptSheet(+ host: String,+ onAllow: () -> Unit,+ onDeny: () -> Unit,+) {+ AlertDialog(+ onDismissRequest = onDeny,+ title = { Text(stringResource(R.string.local_network_title)) },+ text = { Text(stringResource(R.string.local_network_message, host)) },+ confirmButton = { TextButton(onClick = onAllow) { Text(stringResource(R.string.allow)) } },+ dismissButton = { TextButton(onClick = onDeny) { Text(stringResource(R.string.block)) } }+ )+}+ @Composable internal fun FileChooserSheet( mimeTypes: List<String>,
web/src/main/java/com/vayunmathur/web/ui/WebViewBrowser.kt
diff --git a/web/src/main/java/com/vayunmathur/web/ui/WebViewBrowser.kt b/web/src/main/java/com/vayunmathur/web/ui/WebViewBrowser.ktindex 544bec9314..b593f4291d 100644--- a/web/src/main/java/com/vayunmathur/web/ui/WebViewBrowser.kt+++ b/web/src/main/java/com/vayunmathur/web/ui/WebViewBrowser.kt@@ -233,7 +233,12 @@ fun WebViewBrowser( override fun onPageStarted(view: WebView, url: String?, favicon: Bitmap?) { super.onPageStarted(view, url, favicon) viewModel.resetBlockedCount(tabId)- url?.let { viewModel.onTabUrlChange(tabId, it) }+ url?.let {+ viewModel.onTabUrlChange(tabId, it)+ // Catch-all for the loads shouldOverrideUrlLoading never sees:+ // programmatic loadUrl, redirects and session restore.+ viewModel.noteNavigation(it)+ } viewModel.onTabCanGoBack(tabId, view.canGoBack()) viewModel.onTabCanGoForward(tabId, view.canGoForward()) }
web/src/main/res/values/strings.xml
diff --git a/web/src/main/res/values/strings.xml b/web/src/main/res/values/strings.xmlindex 4deeab7b4c..38c4eb0fdb 100644--- a/web/src/main/res/values/strings.xml+++ b/web/src/main/res/values/strings.xml@@ -118,4 +118,8 @@ <string name="copy_link">Copy link</string> <string name="open_in_new_tab">Open in new tab</string> <string name="link_copied">Link copied</string>+ <string name="cleartext_blocked_title">Insecure connection blocked</string>+ <string name="cleartext_blocked_message">%1$s was requested over plain HTTP. Unencrypted connections are only allowed to devices on your local network.</string>+ <string name="local_network_title">Allow local network access?</string>+ <string name="local_network_message">%1$s looks like a device on your network. Android needs local network permission before this page can load.</string> </resources>
web/src/main/res/xml/network_security_config.xml
diff --git a/web/src/main/res/xml/network_security_config.xml b/web/src/main/res/xml/network_security_config.xmlindex e8793eafcb..b121852dda 100644--- a/web/src/main/res/xml/network_security_config.xml+++ b/web/src/main/res/xml/network_security_config.xml@@ -1,8 +1,12 @@ <?xml version="1.0" encoding="utf-8"?> <network-security-config> <!-- Web is a browser: must trust any cert host + user-installed CAs (MITM debug, corp proxies).- No cleartext restriction here beyond WebView defaults — browser needs to load any site. -->- <base-config cleartextTrafficPermitted="false">+ Cleartext is permitted at the platform level because LAN sites (routers, NAS boxes, dev+ servers) are almost all plain http, and this file can only match exact hostnames - there+ is no CIDR syntax, so "cleartext on the LAN only" is not expressible here for a browser+ that navigates wherever the user types. That rule is enforced in the app layer instead,+ by ShieldsRequestFilter via LanPolicy. -->+ <base-config cleartextTrafficPermitted="true"> <trust-anchors> <certificates src="system" /> <certificates src="user" />
web/src/test/java/com/vayunmathur/web/domain/LanPolicyTest.kt
diff --git a/web/src/test/java/com/vayunmathur/web/domain/LanPolicyTest.kt b/web/src/test/java/com/vayunmathur/web/domain/LanPolicyTest.ktnew file mode 100644index 0000000000..d3a3068c7c--- /dev/null+++ b/web/src/test/java/com/vayunmathur/web/domain/LanPolicyTest.kt@@ -0,0 +1,154 @@+package com.vayunmathur.web.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++class LanPolicyTest {++ /** Records every lookup so tests can assert the DNS path is not taken needlessly. */+ private class FakeResolver(+ private val answers: Map<String, List<String>> = emptyMap(),+ private val throwFor: Set<String> = emptySet(),+ ) : HostResolver {+ var calls = 0+ private set++ override fun resolve(host: String): List<String> {+ calls+++ if (host in throwFor) throw java.net.UnknownHostException(host)+ return answers[host] ?: emptyList()+ }+ }++ private class FakeClock(var millis: Long = 0L) : () -> Long {+ override fun invoke(): Long = millis+ }++ @Test+ fun `non-http schemes are allowed without a lookup`() {+ val resolver = FakeResolver()+ val policy = LanPolicy(resolver, FakeClock())+ assertTrue(policy.allowsCleartext("https://example.com/"))+ assertTrue(policy.allowsCleartext("about:blank"))+ assertTrue(policy.allowsCleartext("data:text/html,hi"))+ assertEquals(0, resolver.calls)+ }++ @Test+ fun `syntactically local hosts are allowed without a lookup`() {+ val resolver = FakeResolver()+ val policy = LanPolicy(resolver, FakeClock())+ assertTrue(policy.allowsCleartext("http://nas.local/"))+ assertTrue(policy.allowsCleartext("http://192.168.1.1/"))+ assertTrue(policy.allowsCleartext("http://router/"))+ assertTrue(policy.allowsCleartext("http://[::1]:3000/"))+ assertEquals(0, resolver.calls)+ }++ @Test+ fun `syntactically public hosts are blocked without a lookup`() {+ val resolver = FakeResolver()+ val policy = LanPolicy(resolver, FakeClock())+ assertFalse(policy.allowsCleartext("http://8.8.8.8/"))+ assertEquals(0, resolver.calls)+ }++ @Test+ fun `a private answer is allowed`() {+ val resolver = FakeResolver(mapOf("dev.example.com" to listOf("10.0.0.5")))+ val policy = LanPolicy(resolver, FakeClock())+ assertTrue(policy.allowsCleartext("http://dev.example.com/x"))+ assertEquals(1, resolver.calls)+ }++ @Test+ fun `a public answer is blocked`() {+ val resolver = FakeResolver(mapOf("example.com" to listOf("93.184.216.34")))+ val policy = LanPolicy(resolver, FakeClock())+ assertFalse(policy.allowsCleartext("http://example.com/"))+ }++ @Test+ fun `mixed answers are blocked`() {+ // The DNS-rebinding shape: any-of would be a front door.+ val resolver = FakeResolver(mapOf("evil.example.com" to listOf("10.0.0.5", "93.184.216.34")))+ val policy = LanPolicy(resolver, FakeClock())+ assertFalse(policy.allowsCleartext("http://evil.example.com/"))+ }++ @Test+ fun `an empty answer is blocked`() {+ val resolver = FakeResolver()+ val policy = LanPolicy(resolver, FakeClock())+ assertFalse(policy.allowsCleartext("http://gone.example.com/"))+ }++ @Test+ fun `a throwing resolver is blocked`() {+ val resolver = FakeResolver(throwFor = setOf("broken.example.com"))+ val policy = LanPolicy(resolver, FakeClock())+ assertFalse(policy.allowsCleartext("http://broken.example.com/"))+ }++ @Test+ fun `zone ids in resolved addresses are ignored`() {+ val resolver = FakeResolver(mapOf("link.example.com" to listOf("fe80:0:0:0:0:0:0:1%wlan0")))+ val policy = LanPolicy(resolver, FakeClock())+ assertTrue(policy.allowsCleartext("http://link.example.com/"))+ }++ @Test+ fun `a decided host is only resolved once`() {+ val resolver = FakeResolver(mapOf("dev.example.com" to listOf("10.0.0.5")))+ val policy = LanPolicy(resolver, FakeClock())+ assertTrue(policy.allowsCleartext("http://dev.example.com/a"))+ assertTrue(policy.allowsCleartext("http://dev.example.com/b"))+ assertEquals(1, resolver.calls)+ }++ @Test+ fun `the decision is re-resolved after its TTL`() {+ val clock = FakeClock()+ val resolver = FakeResolver(mapOf("dev.example.com" to listOf("10.0.0.5")))+ val policy = LanPolicy(resolver, clock)+ assertTrue(policy.allowsCleartext("http://dev.example.com/"))+ clock.millis += 5 * 60 * 1000L+ assertTrue(policy.allowsCleartext("http://dev.example.com/"))+ assertEquals(2, resolver.calls)+ }++ @Test+ fun `a failure is retried much sooner than a decision`() {+ val clock = FakeClock()+ val resolver = FakeResolver()+ val policy = LanPolicy(resolver, clock)+ assertFalse(policy.allowsCleartext("http://gone.example.com/"))+ clock.millis += 9_000L+ assertFalse(policy.allowsCleartext("http://gone.example.com/"))+ assertEquals(1, resolver.calls)+ clock.millis += 2_000L+ assertFalse(policy.allowsCleartext("http://gone.example.com/"))+ assertEquals(2, resolver.calls)+ }++ @Test+ fun `clearCache forces a fresh lookup`() {+ val resolver = FakeResolver(mapOf("dev.example.com" to listOf("10.0.0.5")))+ val policy = LanPolicy(resolver, FakeClock())+ assertTrue(policy.allowsCleartext("http://dev.example.com/"))+ policy.clearCache()+ assertTrue(policy.allowsCleartext("http://dev.example.com/"))+ assertEquals(2, resolver.calls)+ }++ @Test+ fun `the cache key is case insensitive`() {+ val resolver = FakeResolver(mapOf("dev.example.com" to listOf("10.0.0.5")))+ val policy = LanPolicy(resolver, FakeClock())+ assertTrue(policy.allowsCleartext("http://DEV.Example.com/"))+ assertTrue(policy.allowsCleartext("http://dev.example.com/"))+ assertEquals(1, resolver.calls)+ }+}
web/src/test/java/com/vayunmathur/web/domain/LocalNetworkTest.kt
diff --git a/web/src/test/java/com/vayunmathur/web/domain/LocalNetworkTest.kt b/web/src/test/java/com/vayunmathur/web/domain/LocalNetworkTest.ktnew file mode 100644index 0000000000..af6b2722eb--- /dev/null+++ b/web/src/test/java/com/vayunmathur/web/domain/LocalNetworkTest.kt@@ -0,0 +1,177 @@+package com.vayunmathur.web.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++class LocalNetworkTest {++ private fun kind(host: String) = LocalNetwork.classify(host)++ // ------------------------------------------------------------------ hostOf++ @Test+ fun `strips userinfo port path query and fragment`() {+ assertEquals("192.168.1.1", LocalNetwork.hostOf("http://user:[email protected]:8080/a?b#c"))+ }++ @Test+ fun `consumes IPv6 brackets before the port`() {+ assertEquals("fe80::1", LocalNetwork.hostOf("http://[fe80::1]:8080/"))+ assertEquals("::1", LocalNetwork.hostOf("http://[::1]:3000"))+ }++ @Test+ fun `cuts an IPv6 zone id`() {+ assertEquals("fe80::1", LocalNetwork.hostOf("http://[fe80::1%25wlan0]/x"))+ }++ @Test+ fun `accepts scheme-less input`() {+ assertEquals("nas.local", LocalNetwork.hostOf("nas.local"))+ assertEquals("192.168.1.1", LocalNetwork.hostOf("192.168.1.1:8080"))+ }++ @Test+ fun `lowercases and drops one trailing dot`() {+ assertEquals("nas.local", LocalNetwork.hostOf("http://NAS.Local./"))+ }++ // -------------------------------------------------------------------- IPv4++ @Test+ fun `respects the 172 16 slash 12 boundaries`() {+ assertEquals(HostKind.PUBLIC, kind("172.15.255.255"))+ assertEquals(HostKind.LAN, kind("172.16.0.0"))+ assertEquals(HostKind.LAN, kind("172.31.255.255"))+ assertEquals(HostKind.PUBLIC, kind("172.32.0.0"))+ }++ @Test+ fun `respects the 192 168 and 169 254 boundaries`() {+ assertEquals(HostKind.PUBLIC, kind("192.167.1.1"))+ assertEquals(HostKind.LAN, kind("192.168.1.1"))+ assertEquals(HostKind.PUBLIC, kind("192.169.1.1"))+ assertEquals(HostKind.PUBLIC, kind("169.253.1.1"))+ assertEquals(HostKind.LAN, kind("169.254.1.1"))+ }++ @Test+ fun `treats loopback and this-network as LAN`() {+ assertEquals(HostKind.LAN, kind("127.0.0.1"))+ assertEquals(HostKind.LAN, kind("10.0.0.1"))+ assertEquals(HostKind.LAN, kind("0.0.0.0"))+ }++ @Test+ fun `CGNAT space is not LAN`() {+ // 100.64/10 is carrier space shared with strangers, not a network the user controls.+ assertEquals(HostKind.PUBLIC, kind("100.64.0.1"))+ }++ @Test+ fun `public addresses are public`() {+ assertEquals(HostKind.PUBLIC, kind("8.8.8.8"))+ assertEquals(HostKind.PUBLIC, kind("1.2.3.4"))+ }++ @Test+ fun `non-canonical numeric forms fail closed`() {+ assertEquals(HostKind.PUBLIC, kind("2130706433"))+ assertEquals(HostKind.PUBLIC, kind("10.1"))+ assertEquals(HostKind.PUBLIC, kind("192.168.1.256"))+ }++ // -------------------------------------------------------------------- IPv6++ @Test+ fun `respects the unique-local boundary`() {+ assertEquals(HostKind.PUBLIC, kind("fb00::1"))+ assertEquals(HostKind.LAN, kind("fc00::1"))+ assertEquals(HostKind.LAN, kind("fd12:3456::1"))+ }++ @Test+ fun `respects the link-local boundary`() {+ assertEquals(HostKind.LAN, kind("fe80::1"))+ assertEquals(HostKind.LAN, kind("febf::1"))+ assertEquals(HostKind.PUBLIC, kind("fec0::1"))+ }++ @Test+ fun `IPv6 loopback is LAN`() {+ assertEquals(HostKind.LAN, kind("::1"))+ }++ @Test+ fun `IPv4-mapped addresses delegate to the IPv4 rules`() {+ assertEquals(HostKind.LAN, kind("::ffff:192.168.1.1"))+ assertEquals(HostKind.PUBLIC, kind("::ffff:8.8.8.8"))+ }++ @Test+ fun `malformed IPv6 is not private`() {+ assertEquals(HostKind.PUBLIC, kind("fc00:::1"))+ assertEquals(HostKind.PUBLIC, kind("fc00::1::2"))+ assertEquals(HostKind.PUBLIC, kind("fc00:1:2:3:4:5:6:7:8"))+ assertEquals(HostKind.PUBLIC, kind("fc00:zzzz::1"))+ }++ @Test+ fun `public IPv6 is public`() {+ assertEquals(HostKind.PUBLIC, kind("2001:4860:4860::8888"))+ }++ // --------------------------------------------------------------- hostnames++ @Test+ fun `local suffixes and dotless hosts are LAN`() {+ assertEquals(HostKind.LAN, kind("localhost"))+ assertEquals(HostKind.LAN, kind("dev.localhost"))+ assertEquals(HostKind.LAN, kind("local"))+ assertEquals(HostKind.LAN, kind("nas.local"))+ assertEquals(HostKind.LAN, kind("home.arpa"))+ assertEquals(HostKind.LAN, kind("router.home.arpa"))+ assertEquals(HostKind.LAN, kind("router"))+ }++ @Test+ fun `a suffix that merely contains local is not LAN`() {+ assertEquals(HostKind.NEEDS_DNS, kind("localhost.evil.com"))+ assertEquals(HostKind.NEEDS_DNS, kind("mylocal.com"))+ assertEquals(HostKind.NEEDS_DNS, kind("notlocalhost.com"))+ }++ @Test+ fun `internal is not treated as local`() {+ // Collides with real cloud-provider zones that resolve publicly.+ assertEquals(HostKind.NEEDS_DNS, kind("db.internal"))+ }++ @Test+ fun `ordinary names need DNS`() {+ assertEquals(HostKind.NEEDS_DNS, kind("example.com"))+ }++ @Test+ fun `an empty host is public`() {+ assertEquals(HostKind.PUBLIC, kind(""))+ }++ // ------------------------------------------------------------- convenience++ @Test+ fun `isIpLiteral covers both families`() {+ assertTrue(LocalNetwork.isIpLiteral("192.168.1.1"))+ assertTrue(LocalNetwork.isIpLiteral("fe80::1"))+ assertFalse(LocalNetwork.isIpLiteral("nas.local"))+ assertFalse(LocalNetwork.isIpLiteral("1.2.3.4.example.com"))+ }++ @Test+ fun `isLanHostSyntactic never says yes for a name that needs DNS`() {+ assertTrue(LocalNetwork.isLanHostSyntactic("nas.local"))+ assertFalse(LocalNetwork.isLanHostSyntactic("example.com"))+ }+}
web/src/test/java/com/vayunmathur/web/domain/shields/UrlCleanerTest.kt
diff --git a/web/src/test/java/com/vayunmathur/web/domain/shields/UrlCleanerTest.kt b/web/src/test/java/com/vayunmathur/web/domain/shields/UrlCleanerTest.ktindex 1c1580f181..dd2cf59f31 100644--- a/web/src/test/java/com/vayunmathur/web/domain/shields/UrlCleanerTest.kt+++ b/web/src/test/java/com/vayunmathur/web/domain/shields/UrlCleanerTest.kt@@ -77,6 +77,25 @@ class UrlCleanerTest { assertNull(UrlCleaner.httpsUpgrade("http://[::1]:9000")) } + @Test+ fun `does not upgrade LAN hosts`() {+ assertNull(UrlCleaner.httpsUpgrade("http://nas.local/"))+ assertNull(UrlCleaner.httpsUpgrade("http://192.168.1.1/"))+ assertNull(UrlCleaner.httpsUpgrade("http://router/"))+ assertNull(UrlCleaner.httpsUpgrade("http://[::1]:3000/"))+ }++ @Test+ fun `does not upgrade public bare IPs either`() {+ // Not LAN, but still has no certificate a public CA would issue.+ assertNull(UrlCleaner.httpsUpgrade("http://1.2.3.4/"))+ }++ @Test+ fun `still upgrades ordinary public hosts`() {+ assertEquals("https://example.com/", UrlCleaner.httpsUpgrade("http://example.com/"))+ }+ @Test fun `upgrades hosts that only look numeric`() { assertEquals("https://1.2.3.4.example.com/", UrlCleaner.httpsUpgrade("http://1.2.3.4.example.com/"))
web/src/test/java/com/vayunmathur/web/platform/BrowserUtilsTest.kt
diff --git a/web/src/test/java/com/vayunmathur/web/platform/BrowserUtilsTest.kt b/web/src/test/java/com/vayunmathur/web/platform/BrowserUtilsTest.ktnew file mode 100644index 0000000000..131b75b9b0--- /dev/null+++ b/web/src/test/java/com/vayunmathur/web/platform/BrowserUtilsTest.kt@@ -0,0 +1,41 @@+package com.vayunmathur.web.platform++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * Only the navigation paths are exercised here. The search fallback goes through+ * `Uri.encode`, which is an unimplemented stub in a JVM unit test, so the "this is a search"+ * cases are asserted through [BrowserUtils.looksLikeUrl] instead.+ */+class BrowserUtilsTest {++ @Test+ fun `LAN-looking input navigates over http`() {+ assertEquals("http://nas.local", BrowserUtils.toNavigationUrl("nas.local"))+ assertEquals("http://192.168.1.1:8080", BrowserUtils.toNavigationUrl("192.168.1.1:8080"))+ assertEquals("http://localhost:3000", BrowserUtils.toNavigationUrl("localhost:3000"))+ }++ @Test+ fun `public input navigates over https`() {+ assertEquals("https://example.com", BrowserUtils.toNavigationUrl("example.com"))+ assertEquals("https://example.com/a?b=1", BrowserUtils.toNavigationUrl("example.com/a?b=1"))+ }++ @Test+ fun `an explicit scheme is kept verbatim`() {+ assertEquals("http://router", BrowserUtils.toNavigationUrl("http://router"))+ assertEquals("http://example.com/", BrowserUtils.toNavigationUrl("http://example.com/"))+ }++ @Test+ fun `input that is not URL-like falls through to search`() {+ assertFalse(BrowserUtils.looksLikeUrl("router"))+ assertFalse(BrowserUtils.looksLikeUrl("hello world"))+ assertTrue(BrowserUtils.looksLikeUrl("nas.local"))+ assertTrue(BrowserUtils.looksLikeUrl("192.168.1.1"))+ }+}