diff --git a/CHANGELOG.md b/CHANGELOG.md index 8b50f14..ca6c15e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,82 @@ before it can reach a release. (There was briefly a separate `sdk:plugin-api` mo third-party plugin framework; it was removed before ever shipping — see Removed, below — so it never joined this list.) +## Unreleased + +Three default changes, aimed at the same complaint: a fresh integration showed a `127.0.0.1` URL +that needed `adb forward` before it displayed anything, and a Mocks screen that could not add a +mock. See [docs/MIGRATION.md](docs/MIGRATION.md#upgrading-from-120) for the upgrade path. + +**Version note, deliberately unresolved here:** under this file's own +[policy](#versioning-and-stability-policy), adding a constant to a public enum is source-breaking +for any host that `when`s exhaustively over `BindingMode`/`BrowserBinding`, and flipping a security +default is a behavioural break. That reads as a major, not a minor. The number is left for the +release decision rather than assumed. + +### Added + +- **`BindingMode.AUTO` and `BrowserBinding.AUTO`**, now the default for `StartRequest.bindingMode` + and `BrowserConfig.binding`. AUTO binds a real network interface when the device has one and + quietly binds loopback when it does not, so a start always yields a working server and the + connect URL is scannable from another machine without configuration. + + Introduced as a third mode rather than by re-pointing the default at `LAN`, because `LAN` earns + its keep by *not* degrading: a host sharing a connect URL with another device needs + `NoEligibleNetwork`/`PermissionRequired` back, not a `127.0.0.1` link that works for nobody but + itself. Explicit `LOOPBACK` and `LAN` behave exactly as before. + + `BrowserEndpoint.bindingMode` never reports `AUTO` — it reports the socket that actually bound, so + the QR code, the connect URL, and the "LAN MODE — UNENCRYPTED" banner stay truthful. AUTO + fallbacks are logged with their reason. + + The name is reused, not restored: the pre-1.0 `BindingMode.AUTO` came with zero-config auto-start + and NSD service discovery, both still removed. This one only picks a binding. + +- **`MockEngineRegistry`** (`sdk:mocks`), a process-wide handle the enabled facade publishes its + `MockEngine` to at `initialize`. It exists to close a module-layering gap — `sdk:network-okhttp` + sits below the facade and cannot call `DevConsole.mockEngine()` — and is what lets + `installDevConsole` wire mocking without the host naming an engine. The protected build publishes + nothing, so a release APK reads `null` and wires no mock interceptor. + +### Changed + +- **The default binding now reaches the network.** This is a deliberate loosening of a security + default: the dashboard speaks plaintext HTTP, so on a network you do not administer, headers, + tokens, and bodies are readable by anyone who can see the traffic. Pass `BindingMode.LOOPBACK` + (and `BrowserConfig(binding = BrowserBinding.LOOPBACK)` for the on-device Start button) to keep + 1.2.0 behaviour. [docs/THREAT_MODEL.md](docs/THREAT_MODEL.md) has been rewritten around the new + default rather than patched. + + One consequence worth knowing: **AUTO never prompts for `ACCESS_LOCAL_NETWORK`.** It treats a + missing grant as a reason to bind loopback, not a reason to fail, so on an API 37+ device it + settles for `127.0.0.1` until something requests the grant. Hosts that want + `StartResult.PermissionRequired` back to drive a prompt ask for `BindingMode.LAN` by name — which + all three samples still do. + +- **`installDevConsole` wires mock rules.** Both the Kotlin extension and the Java-friendly + `DevConsoleOkHttp.install` gained a `mockEngine` parameter defaulting to the published engine, so + the separate `.addInterceptor(DevConsoleMockInterceptor(DevConsole.mockEngine()))` line is no + longer needed. The mock interceptor is added after the capture interceptor, so a served mock is + still recorded and tagged `mocked`. Pass `mockEngine = null` to opt out. + + The 2- and 3-argument overloads are still emitted, so Java call sites and existing bytecode are + unaffected; Kotlin callers relying on default arguments should recompile, since the synthetic + `$default` signature changed. + +- **`EditingCapabilities.mocks` defaults to `true`**, and `DevConsoleConfig` seeds + `EditingCapabilities()` instead of `EditingCapabilities.readOnly()`. A mock rule writes nothing of + the host's — it only short-circuits DevConsole's own interceptor — so the read-only posture that + protects preferences, databases, and files had nothing to protect here. `readOnly()` is now + spelled out field by field rather than delegating to the constructor, so it still grants nothing + at all, mocks included. + +### Fixed + +- **A `Delay` mock rule is no longer applied twice** when a host keeps its own + `DevConsoleMockInterceptor` alongside the one `installDevConsole` now adds. The second interceptor + recognises the first one's request tag and stands down. Without this, upgrading would have + silently doubled every simulated latency that proceeds up the chain. + ## 1.2.0 — 2026-08-15 A minor under the [policy](#versioning-and-stability-policy): the Remote Config inspector is diff --git a/README.md b/README.md index fec99b4..333ed35 100644 --- a/README.md +++ b/README.md @@ -76,12 +76,17 @@ way your manifest needs `INTERNET`, which most apps already declare: ```kotlin lifecycleScope.launch { // startBrowser is a suspend function; the server never starts on its own - val result = DevConsole.startBrowser(StartRequest(bindingMode = BindingMode.LOOPBACK)) + val result = DevConsole.startBrowser(StartRequest()) val connectUrl = (result as? StartResult.Started)?.access?.connectUrl - // e.g. http://127.0.0.1:8080/#code=B7KQ2XWZ — surface this in your debug UI + // e.g. http://192.168.0.15:8080/#code=B7KQ2XWZ — surface this in your debug UI } ``` +The default binding is `BindingMode.AUTO`: it binds your device's network address when there is one, +so the URL opens from any machine on the same Wi-Fi, and falls back to `127.0.0.1` when there isn't. +If it fell back — or if you passed `BindingMode.LOOPBACK` to keep it off the network on purpose — +forward the port first: + ```bash adb forward tcp:8080 tcp:8080 # use the port from the DevConsole log line ``` @@ -89,6 +94,11 @@ adb forward tcp:8080 tcp:8080 # use the port from the DevConsole log line Then open the **whole URL**. The `#code=` fragment is the credential, so a bare `http://host:port/` gets you nothing. +> **The dashboard speaks plaintext HTTP.** On a network address, everything it shows — headers, +> tokens, bodies — is readable by anyone who can see your traffic. That is fine on a home or office +> Wi-Fi and a bad idea on a conference or café network. Pass `BindingMode.LOOPBACK` to rule it out, +> and read [the threat model](docs/THREAT_MODEL.md). + ## What you get | Area | What it does | @@ -96,7 +106,7 @@ gets you nothing. | **In-app inspector** | `DevConsole.open(context)` shows every inspector below as an on-device screen (included with `devconsole`), plus a QR code for pairing the browser. Opens by shake (adjustable intensity) or draggable floating button via the opt-in `DevConsoleConfig.openTriggers` flags. Its More screen can also start and stop the dashboard server. | | **Network inspector** | Every HTTP call with headers, bodies, and a DNS/TCP/TLS/send/wait/receive timing bar. Live-tails as traffic happens. | | **WebSocket & MQTT inspectors** | Connection lifecycles and every frame, inbound and outbound. MQTT rides the Eclipse Paho adapter. | -| **Mock rules** | Serve canned responses for matching requests (OkHttp), toggled from the dashboard, with deterministic priority matching. | +| **Mock rules** | Serve canned responses for matching requests (OkHttp), toggled from the dashboard, with deterministic priority matching. Wired by `installDevConsole` and editable out of the box. | | **Request composer** | Make the device issue ad-hoc HTTP requests from the dashboard. Off by default, host-allowlist confinable. | | **Crash & ANR capture** | Uncaught exceptions and a main-looper watchdog with bounded all-thread dumps and breadcrumbs. Always delegates to any crash reporter you already have. | | **Push timeline** | Record FCM (or any) push messages and their lifecycle: received → displayed → opened. The Firebase adapter uses reflection — no compile-time Firebase dependency. | @@ -165,16 +175,23 @@ scan from another machine.

More screen with the server started, showing the connect URL and QR code

-That button binds **loopback** by default, so the URL it shows needs `adb forward`. To bind LAN -instead, which is what makes the QR code scannable from another machine, declare it on the config. -The button issues no `StartRequest` of its own: +That button binds **AUTO** by default, so on a device with a live Wi-Fi or Ethernet connection the +QR code is scannable from another machine straight away, and on one without it the URL falls back to +`127.0.0.1` and needs `adb forward`. The button issues no `StartRequest` of its own, so if you want +to pin it, declare it on the config: ```kotlin +// Never touch the network: +DevConsoleConfig.default().withBrowserConfig(BrowserConfig(binding = BrowserBinding.LOOPBACK)) + +// Require the network — fails loudly instead of falling back, and surfaces the +// ACCESS_LOCAL_NETWORK prompt on API 37+ devices: DevConsoleConfig.default().withBrowserConfig(BrowserConfig(binding = BrowserBinding.LAN)) ``` This is independent of the `bindingMode` you pass to `startBrowser` yourself; set both if you start -the server from your own UI too. Read [the threat model](docs/THREAT_MODEL.md) before choosing LAN. +the server from your own UI too. Read [the threat model](docs/THREAT_MODEL.md) before leaving either +one on the network. From code: @@ -183,13 +200,14 @@ From code: DevConsole.initialize(application, DevConsoleConfig.default()) // startBrowser and stop are suspend functions — call them from a coroutine: -val result = DevConsole.startBrowser(StartRequest(bindingMode = BindingMode.LOOPBACK)) +val result = DevConsole.startBrowser(StartRequest()) // BindingMode.AUTO when (result) { is StartResult.Started -> { - result.endpoint // host + port actually bound + result.endpoint // host + port actually bound; bindingMode is LOOPBACK or LAN, + // never AUTO — it reports the socket, not the request result.access.connectUrl // the full credential URL — treat as a secret } - is StartResult.PermissionRequired -> { /* LAN only: request result.permission */ } + is StartResult.PermissionRequired -> { /* explicit LAN only: request result.permission */ } else -> { /* NoEligibleNetwork, ServerUnavailable, ... */ } } @@ -214,7 +232,7 @@ DevConsole.startBrowserAsync(request, result -> runOnUiThread(() -> { After `startBrowser`, filter Logcat on the `DevConsole` tag: ```text -I/DevConsole: Dashboard available at: http://127.0.0.1:8080/ (access link available through the DevConsole API/launcher; binding: LOOPBACK) +I/DevConsole: Dashboard available at: http://192.168.0.15:8080/ (access link available through the DevConsole API/launcher; binding: LAN) ``` **The session code is deliberately absent from Logcat.** The full URL, with its `#code= tcp:`, then open the connect URL. -- **LAN:** pass `BindingMode.LAN` and open the URL from any device on the same network. Read - [the threat model](docs/THREAT_MODEL.md) first, because the dashboard speaks plaintext HTTP. A - LAN start that finds no eligible network interface returns `StartResult.NoEligibleNetwork`. It - never quietly falls back to loopback, or the other way around. +- **AUTO (default):** binds your device's network address when it has one, so you open the connect + URL — or scan its QR code — from any machine on the same network with nothing else to set up. With + no usable interface, or without the `ACCESS_LOCAL_NETWORK` grant on an API 37+ device, it binds + `127.0.0.1` instead and the log line says so. Read [the threat model](docs/THREAT_MODEL.md), + because the dashboard speaks plaintext HTTP wherever it lands. +- **LOOPBACK:** run `adb forward tcp: tcp:`, then open the connect URL. Choose this to + keep the dashboard off the network entirely. +- **LAN:** like AUTO, except it refuses to settle. No eligible interface returns + `StartResult.NoEligibleNetwork` and a missing grant returns `StartResult.PermissionRequired` — + neither quietly becomes loopback. Ask for it when a `127.0.0.1` URL would be useless to you, or + when you want that `PermissionRequired` so your app can prompt for the permission. AUTO never + prompts; it just settles for loopback. + +`StartResult.Started.endpoint.bindingMode` always tells you which one you actually got. Open the **whole URL**. The `#code=` fragment is the credential. It is single-use, expires in five minutes, and creates a session immediately with no approval step. A bare `http://host:port/` sits @@ -237,10 +264,9 @@ unauthenticated forever. If a code lapses, issue a fresh one from the device. ### Wire up your network stack ```kotlin -// OkHttp / Retrofit — capture + timing in one call: +// OkHttp / Retrofit — capture, timing, and mock rules in one call: val client = OkHttpClient.Builder() .installDevConsole(DevConsole.networkRecorder()) - .addInterceptor(DevConsoleMockInterceptor(DevConsole.mockEngine())) // optional, mocks .build() // Ktor client, any engine (captures request + response bodies, textual, up to 256 KiB each): @@ -425,12 +451,16 @@ resolved runtime classpath, and the final APK/AAB bytes. See ## Security model -DevConsole deliberately exposes your app's internals to a browser. It defaults to the safe end of -every choice, but you should know where the edges are: +DevConsole deliberately exposes your app's internals to a browser, and two of its defaults trade +safety for a working first run. Know where the edges are: -- **The dashboard speaks plaintext HTTP.** There is no TLS. In LAN mode, anyone who can watch your - network packets can read everything it shows: headers, tokens, bodies, exports. That is why - loopback plus `adb forward` is the default and LAN is always an explicit opt-in. +- **The dashboard speaks plaintext HTTP, and the default binding reaches your network.** There is no + TLS. `BindingMode.AUTO` binds your device's network address whenever it can, so anyone who can + watch your Wi-Fi packets can read everything the dashboard shows: headers, tokens, bodies, + exports. This is a debug-build-only surface behind a single-use expiring credential, which is why + the default favours reachability — but on an untrusted network (a conference, a café, a shared + office VLAN) pass `BindingMode.LOOPBACK`, or set + `BrowserConfig(binding = BrowserBinding.LOOPBACK)`, and use `adb forward`. - **The connect URL is a credential.** Holding a live `#code=` fragment creates a session, with no approval step on the device. Codes are single-use and expire in five minutes; sessions last 30. Treat the URL like a password. You can revoke sessions from the More screen. @@ -439,9 +469,12 @@ every choice, but you should know where the edges are: [docs/SECURITY_AND_REDACTION.md](docs/SECURITY_AND_REDACTION.md). - **Screenshots cannot be redacted.** Pixels don't have field names. Capture is **off by default** and everything it produces is marked `UNREDACTED`. -- **Editing is off by default.** Preferences/database/file writes, mock editing, and capture-rule - editing are each gated per surface via `EditingCapabilities`; the composer and state mutation - have their own `DevConsoleConfig` flags. Everything defaults to off/read-only. +- **Editing is off by default, except mocks.** Preferences/database/file writes and capture-rule + editing are each gated per surface via `EditingCapabilities`; the composer and state mutation have + their own `DevConsoleConfig` flags. All of those default to off/read-only. Mock editing is the one + exception: a mock rule writes nothing of yours, it only short-circuits DevConsole's own + interceptor, so it ships editable. `EditingCapabilities.readOnly()` still refuses everything + including mocks. For the full analysis, including what a malicious network peer or a co-installed app can and cannot do, read [docs/THREAT_MODEL.md](docs/THREAT_MODEL.md). diff --git a/docs/COMPOSER_AND_MOCKS.md b/docs/COMPOSER_AND_MOCKS.md index c8ff893..22cc9e9 100644 --- a/docs/COMPOSER_AND_MOCKS.md +++ b/docs/COMPOSER_AND_MOCKS.md @@ -20,22 +20,31 @@ collections never persist secret variable values by default. ## Mocks -Mocks need one line of host wiring — an OkHttp interceptor that consults the same `MockEngine` -instance the dashboard controls: +Mocks need no host wiring beyond the network installer you already have: ```kotlin val client = OkHttpClient.Builder() - .installDevConsole(DevConsole.networkRecorder()) // capture + timing first - .addInterceptor(DevConsoleMockInterceptor(DevConsole.mockEngine())) // then mock + .installDevConsole(DevConsole.networkRecorder()) // capture + timing + mocks .build() ``` -`installDevConsole` (see [NETWORK_ADAPTERS.md](NETWORK_ADAPTERS.md)) is the recommended way to add -the capture interceptor — it also wires the event listener needed for the Network inspector's -timing bar, which a bare `DevConsoleOkHttpInterceptor(recorder)` does not. +`installDevConsole` (see [NETWORK_ADAPTERS.md](NETWORK_ADAPTERS.md)) adds the capture interceptor, +the event listener needed for the Network inspector's timing bar (which a bare +`DevConsoleOkHttpInterceptor(recorder)` does not), and — from the engine `DevConsole.initialize` +published to `MockEngineRegistry` — the mock interceptor, in that order. Order matters: the capture +interceptor goes first, so a mocked response is still captured and tagged like a normal response +(matching the interception order in the spec). -Order matters: put the capture interceptor before the mock interceptor, so a mocked response is -still captured and tagged like a normal response (matching the interception order in the spec). +Two escape hatches. Pass `mockEngine = null` to install no mock interceptor at all, or pass an +engine of your own to mock against something other than the live one: + +```kotlin +.installDevConsole(DevConsole.networkRecorder(), mockEngine = null) +``` + +If you are upgrading and already had `.addInterceptor(DevConsoleMockInterceptor(DevConsole.mockEngine()))`, +you can delete it. Leaving it in place is safe — the second interceptor sees the first one's tag and +stands down, so a `Delay` rule is never applied twice — but it no longer does anything. Rules are created from the dashboard, not from host code — a rule matches on method/scheme/host/ path (regex) plus optional query/header/body predicates, and resolves to an action: a static @@ -59,9 +68,12 @@ The same dashboard button turns mocking back on (it reads its label from the eng as does the Android inspector's Control screen. The two directions gate differently on purpose: turning mocking *off* needs only an authenticated session, since falling back to real traffic is always a safe thing to allow, while turning it back *on* also needs the host's `mocks` editing -capability, because it changes how the app behaves. A host that publishes rules read-only -(`EditingCapabilities(mocks = false)`) can therefore disable mocking from the browser but not -re-enable it — the engine is still switchable in-process through `DevConsole.mockEngine()`. +capability, because it changes how the app behaves. `mocks` is the one editing capability that +defaults to *on* — a mock rule writes nothing of the host's, it only short-circuits DevConsole's own +interceptor — so this asymmetry bites only a host that opted back out. One that publishes rules +read-only (`EditingCapabilities(mocks = false)`, or `EditingCapabilities.readOnly()`) can therefore +disable mocking from the browser but not re-enable it — the engine is still switchable in-process +through `DevConsole.mockEngine()`. Individual rules toggle independently of this switch; with the engine off, no rule applies regardless of its own state. diff --git a/docs/DATA_INSPECTORS_AND_EXPORTS.md b/docs/DATA_INSPECTORS_AND_EXPORTS.md index e23332c..24db89d 100644 --- a/docs/DATA_INSPECTORS_AND_EXPORTS.md +++ b/docs/DATA_INSPECTORS_AND_EXPORTS.md @@ -5,8 +5,10 @@ than network/socket/push traffic: the **Data** inspectors (preferences, database device's **More** screen, and the **export** formats (HAR, Postman, and the Android session ZIP). All of it sits behind the same SESSION_CODE auth as everything else — see [PROTOCOL_REFERENCE.md](PROTOCOL_REFERENCE.md#2-auth-handshake-session_code) — and every mutating -action additionally gates on the host's `EditingCapabilities`, which default to all-`false` -(`EditingCapabilities.readOnly()`). A host opts specific features in: +action additionally gates on the host's `EditingCapabilities`. Every one of them defaults to `false` +except `mocks`, which ships editable because a mock rule writes nothing of the host's — it only +short-circuits DevConsole's own interceptor. `EditingCapabilities.readOnly()` still refuses +everything, mocks included. A host opts specific features in: ```kotlin DevConsole.initialize( diff --git a/docs/FAQ_TROUBLESHOOTING.md b/docs/FAQ_TROUBLESHOOTING.md index 0be1a59..d6669f3 100644 --- a/docs/FAQ_TROUBLESHOOTING.md +++ b/docs/FAQ_TROUBLESHOOTING.md @@ -1,12 +1,20 @@ # FAQ / troubleshooting -**Can I connect from another machine on the same network?** Yes. Pass `BindingMode.LAN` to -`startBrowser(...)`, then open the connect URL or scan the QR code from the other device. Loopback -plus `adb forward` is still the safer default. Only reach for LAN on a network you trust, because -the dashboard speaks plaintext HTTP. See -[LAN_PERMISSION_AND_TROUBLESHOOTING.md](LAN_PERMISSION_AND_TROUBLESHOOTING.md) and +**Can I connect from another machine on the same network?** Usually with no setup at all — the +default `BindingMode.AUTO` binds your device's network address whenever there is one, so the connect +URL and its QR code already work from another device. If you got a `127.0.0.1` URL, AUTO fell back +(no eligible interface, or an ungranted `ACCESS_LOCAL_NETWORK` on API 37+); Logcat names the reason. +Pass `BindingMode.LAN` to make that a hard failure instead of a fallback. Because the dashboard +speaks plaintext HTTP, pass `BindingMode.LOOPBACK` and use `adb forward` on any network you do not +trust. See [LAN_PERMISSION_AND_TROUBLESHOOTING.md](LAN_PERMISSION_AND_TROUBLESHOOTING.md) and [THREAT_MODEL.md](THREAT_MODEL.md). +**Do I need a second interceptor for mock rules?** No. `installDevConsole(...)` wires the mock +interceptor from the engine DevConsole publishes at `initialize`, so `DevConsoleMockInterceptor` no +longer needs to be added by hand. Keeping an existing manual line is harmless — the second +interceptor detects the first and stands down — but you can delete it. Mock editing is also on by +default now; `EditingCapabilities.readOnly()` turns it back off. + **Why does my release build still contain `sdk:network`/`sdk:state`/... classes?** Those five domain modules (network, socket, push, state, mocks) are pure-Kotlin contract types with no Android/OkHttp/Ktor dependency, and `sdk:api` depends on them directly so the public facade can diff --git a/docs/LAN_PERMISSION_AND_TROUBLESHOOTING.md b/docs/LAN_PERMISSION_AND_TROUBLESHOOTING.md index 918b578..4a86394 100644 --- a/docs/LAN_PERMISSION_AND_TROUBLESHOOTING.md +++ b/docs/LAN_PERMISSION_AND_TROUBLESHOOTING.md @@ -6,6 +6,10 @@ DevConsole.startBrowser(StartRequest(bindingMode = BindingMode.LAN, portRange = 8080..8099)) ``` +> The default, `BindingMode.AUTO`, does the same thing when it can and binds loopback when it +> cannot — see [AUTO binding](#auto-binding) below. Everything in this section describes what both +> modes do on the successful path; they differ only in how they fail. + `KtorLocalServerEngine` enumerates the device's network interfaces and binds to the first active, non-loopback IPv4 address it finds on an interface that is up and not virtual or point-to-point (this excludes loopback, VPN/tun interfaces, and cellular PPP-style links; it does not try to @@ -53,6 +57,38 @@ Requesting it at runtime is still your app's job — use `ActivityResultContract with `StartResult.PermissionRequired.permission` when you get that result back, exactly as all three samples do. +## AUTO binding + +`BindingMode.AUTO` is what a bare `StartRequest()` means, and what an unconfigured +`BrowserConfig.binding` declares for the in-app Start button. It attempts LAN and falls back to +loopback rather than failing: + +| | LAN available | No eligible interface | `ACCESS_LOCAL_NETWORK` ungranted (API 37+) | +|---|---|---|---| +| `AUTO` | binds LAN | binds loopback | binds loopback | +| `LAN` | binds LAN | `NoEligibleNetwork` | `PermissionRequired` | +| `LOOPBACK` | binds loopback | binds loopback | binds loopback | + +The permission is checked *before* the first bind attempt, not discovered by failing one, so an +ungranted AUTO start costs nothing extra. When AUTO does fall back, the reason is logged: + +```text +I/DevConsole: LAN is unavailable (NoEligibleNetwork(detail=...)); binding loopback instead +``` + +**AUTO never asks for the local-network permission.** It treats a missing grant as a reason to +settle for loopback, not a reason to prompt, so on an API 37+ device an AUTO start quietly serves +`127.0.0.1` forever unless something requests `ACCESS_LOCAL_NETWORK`. If you want the prompt, ask +for `BindingMode.LAN` by name and act on the `StartResult.PermissionRequired` it returns — that is +what all three samples do. + +Read the mode you actually got from `StartResult.Started.endpoint.bindingMode`. It reports the +socket rather than the request, and is never `AUTO`. + +Reusing this name is deliberate but narrow: a pre-1.0 `BindingMode.AUTO` existed alongside +zero-config auto-start and NSD service discovery and was removed with them. This one is a binding +preference only — it discovers nothing and starts nothing on its own. + ## Loopback / ADB reverse mode Still the safer default when you don't need cross-device access: @@ -77,9 +113,16 @@ that same result). **`StartResult.PortUnavailable`** — every port in the configured range is already bound. Either free one of the ports or pass a wider/different `portRange`. -**`StartResult.NoEligibleNetwork`** — LAN mode was requested but no active, non-loopback interface -was found. Confirm Wi-Fi (or another LAN connection) is actually connected, not just associated; -airplane mode, a VPN-only connection, or a cellular-only connection will all trigger this. +**`StartResult.NoEligibleNetwork`** — `BindingMode.LAN` was requested explicitly but no active, +non-loopback interface was found. Confirm Wi-Fi (or another LAN connection) is actually connected, +not just associated; airplane mode, a VPN-only connection, or a cellular-only connection will all +trigger this. `BindingMode.AUTO` never returns this — it binds loopback instead. + +**Connect URL is `127.0.0.1` when you expected a LAN address** — you are on `BindingMode.AUTO` and +it fell back. Check Logcat for the `LAN is unavailable (...); binding loopback instead` line, which +names the reason. The two causes are no eligible interface (see above) and, on API 37+ devices, an +ungranted `ACCESS_LOCAL_NETWORK` — AUTO will not prompt for it, so request it yourself or switch +that start to `BindingMode.LAN`. **Connect URL doesn't load** — for LAN mode, confirm the other device is actually on the same subnet/network (a guest Wi-Fi network with client isolation enabled will block this even though diff --git a/docs/MIGRATION.md b/docs/MIGRATION.md index 5b76907..1f20646 100644 --- a/docs/MIGRATION.md +++ b/docs/MIGRATION.md @@ -9,6 +9,59 @@ Validate each debug and release variant with `verifyDevConsoleProtectedArtifacts` before rollout. +## Upgrading from 1.2.0 + +Three defaults changed. No API was removed and nothing has to be rewritten — but two of these change +behaviour on a build you do not otherwise touch, so read them before upgrading. + +**1. The server now binds your network by default.** `StartRequest.bindingMode` and +`BrowserConfig.binding` default to a new `AUTO` value instead of `LOOPBACK`. AUTO binds a real +interface when the device has one and falls back to loopback when it does not, so a start that used +to hand back `http://127.0.0.1:8080/...` now hands back `http://192.168.x.y:8080/...` — reachable by +anyone on that network, over plaintext HTTP. + +To keep 1.2.0 behaviour exactly, say so at both surfaces: + +```kotlin +DevConsole.startBrowser(StartRequest(bindingMode = BindingMode.LOOPBACK)) +DevConsoleConfig.default().withBrowserConfig(BrowserConfig(binding = BrowserBinding.LOOPBACK)) +``` + +Explicit `BindingMode.LAN` is unchanged, including its refusal to fall back. Note that `AUTO` never +returns `StartResult.PermissionRequired`, so if your app prompts for `ACCESS_LOCAL_NETWORK` off the +back of that result, keep asking for `LAN` by name on the start that drives the prompt. + +`AUTO` is a reused name, not a restored feature: the pre-1.0 `BindingMode.AUTO` came with +zero-config auto-start and NSD discovery, both still gone. This one only picks a binding. + +**If you `when` exhaustively over `BindingMode` or `BrowserBinding`**, the new constant makes that +`when` non-exhaustive and your build will fail until you add a branch. This is the only source-level +break in the release. + +**2. Mock rules are wired by `installDevConsole`.** Delete the now-redundant line if you have it: + +```diff + val client = OkHttpClient.Builder() + .installDevConsole(DevConsole.networkRecorder()) +- .addInterceptor(DevConsoleMockInterceptor(DevConsole.mockEngine())) + .build() +``` + +Leaving it costs nothing — the second interceptor detects the first and stands down, so a `Delay` +rule is not applied twice. Pass `mockEngine = null` to opt out of the mock interceptor entirely. + +Kotlin callers who rely on default arguments should recompile: `installDevConsole` and +`DevConsoleOkHttp.install` gained a parameter, so their synthetic `$default` signature changed. The +2- and 3-argument overloads are still emitted, so Java call sites and existing bytecode are +unaffected. + +**3. Mock editing is on by default.** `EditingCapabilities.mocks` now defaults to `true`, and +`DevConsoleConfig` seeds `EditingCapabilities()` rather than `EditingCapabilities.readOnly()`. A +mock rule writes nothing of yours — it only short-circuits DevConsole's own interceptor — so the +read-only posture that protects preferences, databases, and files had nothing to protect here. +`EditingCapabilities.readOnly()` still grants nothing at all, mocks included, so a host already +calling it is unaffected. + ## Pre-1.0 breaking changes The SDK is pre-1.0 (see [CHANGELOG.md](../CHANGELOG.md)), so the API surface above has moved more diff --git a/docs/THREAT_MODEL.md b/docs/THREAT_MODEL.md index d1add8d..194fbd2 100644 --- a/docs/THREAT_MODEL.md +++ b/docs/THREAT_MODEL.md @@ -6,12 +6,21 @@ is the honest version of that trade-off. Read it before turning on LAN mode. ## The one-paragraph summary -The dashboard is served over **plaintext HTTP**. There is no TLS anywhere in this SDK. In LAN mode -the bearer token, every captured request and response header, every WebSocket frame, every push -payload, and every HAR export cross the network unencrypted. Anyone in a position to observe that -traffic — another device on the same Wi-Fi, a compromised router, a guest network operator, someone -running a packet capture in a café — reads all of it. **Loopback plus `adb forward` avoids this -entirely and should be your default.** +The dashboard is served over **plaintext HTTP**. There is no TLS anywhere in this SDK. Whenever the +server is bound to a network address, the bearer token, every captured request and response header, +every WebSocket frame, every push payload, and every HAR export cross the network unencrypted. +Anyone in a position to observe that traffic — another device on the same Wi-Fi, a compromised +router, a guest network operator, someone running a packet capture in a café — reads all of it. + +**The default binding reaches the network.** `BindingMode.AUTO` — what a bare +`StartRequest()` and an unconfigured `BrowserConfig` both mean — binds a real interface whenever the +device has one, and only falls back to `127.0.0.1` when it does not. Reachability is the default +because a debug-only dashboard that needs an `adb forward` incantation before it shows anything is a +dashboard most people never see. **The exposure is real regardless of the reasoning: on any network +you do not administer, pass `BindingMode.LOOPBACK` (and set +`BrowserConfig(binding = BrowserBinding.LOOPBACK)` for the on-device Start button).** Loopback plus +`adb forward` still avoids this entire class of attack; it is now something you ask for rather than +something you get. ## Screenshots are unredactable by construction @@ -173,8 +182,8 @@ Bodies are also truncated to 64 KiB before storage. That is a resource bound, no ## Safe defaults -**Untrusted or shared network — use loopback.** This is the recommended posture and the SDK's own -default binding mode: +**Untrusted or shared network — use loopback.** This is the recommended posture, and it is no +longer the SDK's default: you have to ask for it. ```kotlin DevConsole.startBrowser(StartRequest(bindingMode = BindingMode.LOOPBACK)) @@ -193,19 +202,32 @@ reasonable place for LAN mode. A conference Wi-Fi, a hotel, a café, or any netw administer is not. Note that LAN mode binds one specific interface address, never `0.0.0.0`, which limits reach but does not make the traffic private. -**LAN mode is always an explicit opt-in.** `startBrowser()` never picks a binding mode for you -- -the default `StartRequest()` binds loopback, and LAN only happens when you pass -`bindingMode = BindingMode.LAN` yourself. So on a network you do not trust, simply don't ask for -LAN: +**Staying off the network is the explicit choice.** This used to be the other way round. +`startBrowser()` +picks `BindingMode.AUTO` when you pass no mode, and AUTO reaches the network whenever it can. On a +network you do not trust, say so: `DevConsole.startBrowser(StartRequest(bindingMode = BindingMode.LOOPBACK))`. -There is a second way to start the server, and it has its own opt-in: the **Start button on the -in-app inspector's More screen**, which issues no `StartRequest` and instead binds whatever -`DevConsoleConfig.browserConfig.binding` declares. That field also defaults to `LOOPBACK`, so an -on-device start is loopback unless a host explicitly configures -`BrowserConfig(binding = BrowserBinding.LAN)`. The two settings are independent and neither -overrides the other -- a host that wants LAN from both surfaces has to say so twice, and a host that -sets only `StartRequest(bindingMode = LAN)` leaves the on-device button on loopback. +The three modes differ only in what they do when LAN is unavailable: + +| Mode | Network available | No eligible interface | `ACCESS_LOCAL_NETWORK` ungranted (API 37+) | +|---|---|---|---| +| `AUTO` (default) | binds LAN | binds loopback | binds loopback | +| `LAN` | binds LAN | `NoEligibleNetwork` | `PermissionRequired` | +| `LOOPBACK` | binds loopback | binds loopback | binds loopback | + +Two consequences worth internalising. First, **AUTO never prompts for the local-network +permission** — it treats a missing grant as a reason to settle rather than a reason to ask — so on an +API 37+ device an AUTO start quietly serves `127.0.0.1` until something requests the grant. Ask for +`LAN` by name if you want the `PermissionRequired` result to drive a prompt. Second, +`StartResult.Started.endpoint.bindingMode` is the only honest answer to "did this reach the +network?"; it reports the socket, never the request, and is never `AUTO`. + +There is a second way to start the server: the **Start button on the in-app inspector's More +screen**, which issues no `StartRequest` and instead binds whatever +`DevConsoleConfig.browserConfig.binding` declares. That field defaults to `BrowserBinding.AUTO` too. +The two settings are independent and neither overrides the other -- a host that wants to pin one +surface to loopback has to say so on that surface. **Stop the server when you are done.** `DevConsole.stop(...)` revokes browser sessions immediately and unbinds the port. A dashboard left running on a desk overnight is an open dashboard. diff --git a/samples/compose-app/src/main/kotlin/io/devconsole/sample/compose/MainActivity.kt b/samples/compose-app/src/main/kotlin/io/devconsole/sample/compose/MainActivity.kt index fdc6997..66156d0 100644 --- a/samples/compose-app/src/main/kotlin/io/devconsole/sample/compose/MainActivity.kt +++ b/samples/compose-app/src/main/kotlin/io/devconsole/sample/compose/MainActivity.kt @@ -91,7 +91,6 @@ import io.devconsole.api.StartResult import io.devconsole.api.StopReason import io.devconsole.mocks.MockAction import io.devconsole.mocks.MockRule -import io.devconsole.mocks.okhttp.DevConsoleMockInterceptor import io.devconsole.network.okhttp.installDevConsole import io.devconsole.push.PushInput import io.devconsole.remoteconfig.RemoteConfigEntry @@ -264,8 +263,8 @@ class MainActivity : ComponentActivity() { // Wires the event listener and interceptor together so the Network inspector's timing // bar (DNS/connect/TLS/send/wait/receive) is actually populated -- see the kdoc on // installDevConsole for why the equivalent three-step manual form is easy to get wrong. + // Mock rules ride along on the same call, from the engine published at initialize. .installDevConsole(DevConsole.networkRecorder()) - .addInterceptor(DevConsoleMockInterceptor(DevConsole.mockEngine())) .build() } diff --git a/samples/foundation-app/src/main/kotlin/io/devconsole/sample/MainActivity.kt b/samples/foundation-app/src/main/kotlin/io/devconsole/sample/MainActivity.kt index d55364a..86778a5 100644 --- a/samples/foundation-app/src/main/kotlin/io/devconsole/sample/MainActivity.kt +++ b/samples/foundation-app/src/main/kotlin/io/devconsole/sample/MainActivity.kt @@ -37,7 +37,6 @@ import io.devconsole.api.StartResult import io.devconsole.api.StopReason import io.devconsole.mocks.MockAction import io.devconsole.mocks.MockRule -import io.devconsole.mocks.okhttp.DevConsoleMockInterceptor import io.devconsole.network.okhttp.installDevConsole import io.devconsole.push.PushInput import io.devconsole.socket.okhttp.DevConsoleOkHttpWebSocketListener @@ -88,10 +87,11 @@ private const val ANR_BLOCK_MS = 6_000L * button below exercises exactly one capability so it can be tested in isolation. * * Capability-flag posture (see compose-app's `MainActivity` for the full three-sample matrix): - * every [EditingCapabilities] flag is left at its `false` default here, on purpose -- this sample - * is the locked-down contrast to compose-app's fully-unlocked one. The Data rail (preferences/ - * database/files, seeded below) is still visible and browsable in both the browser dashboard and - * the SDK's in-app inspector; only the write/edit actions are refused. + * [EditingCapabilities.readOnly] refuses every write here, on purpose -- this sample is the + * locked-down contrast to compose-app's fully-unlocked one. Note that this now takes an explicit + * call: the SDK's own default leaves `mocks` editable, and `readOnly()` is what opts back out. The + * Data rail (preferences/database/files, seeded below) is still visible and browsable in both the + * browser dashboard and the SDK's in-app inspector; only the write/edit actions are refused. * * Screenshot capture follows the same posture: `ScreenshotPolicy.enabled` is left at its SDK-wide * `false` default (no `withScreenshotPolicy` override), so the "Capture screenshot" button here @@ -110,9 +110,10 @@ class MainActivity : Activity() { OkHttpClient .Builder() // One-call installer: wires the event listener factory and the interceptor together so - // the Network inspector's timing bar (DNS/connect/TLS/send/wait/receive) is populated. + // the Network inspector's timing bar (DNS/connect/TLS/send/wait/receive) is populated, + // and wires mock rules from the engine DevConsole published at initialize -- no separate + // DevConsoleMockInterceptor line needed. .installDevConsole(DevConsole.networkRecorder()) - .addInterceptor(DevConsoleMockInterceptor(DevConsole.mockEngine())) .build() } diff --git a/samples/views-java-app/src/main/java/io/devconsole/sample/viewsjava/MainActivity.java b/samples/views-java-app/src/main/java/io/devconsole/sample/viewsjava/MainActivity.java index 2a40a90..421bc7f 100644 --- a/samples/views-java-app/src/main/java/io/devconsole/sample/viewsjava/MainActivity.java +++ b/samples/views-java-app/src/main/java/io/devconsole/sample/viewsjava/MainActivity.java @@ -52,7 +52,6 @@ import io.devconsole.mocks.MockAction; import io.devconsole.mocks.MockRule; import io.devconsole.mocks.MockScope; -import io.devconsole.mocks.okhttp.DevConsoleMockInterceptor; import io.devconsole.network.okhttp.DevConsoleOkHttp; import io.devconsole.push.PushEvent; import io.devconsole.push.PushInput; @@ -152,9 +151,9 @@ public final class MainActivity extends Activity { // DevConsoleOkHttp.install() is the Java-friendly one-call installer: it wires the event // listener factory and interceptor together so the Network inspector's timing bar // (DNS/connect/TLS/send/wait/receive) is populated -- see its kdoc for why the equivalent - // manual three-step form is easy to get wrong from Java. + // manual three-step form is easy to get wrong from Java. Mock rules come with it, from the + // engine DevConsole published at initialize, so no DevConsoleMockInterceptor line is needed. client = DevConsoleOkHttp.install(new OkHttpClient.Builder(), DevConsole.networkRecorder()) - .addInterceptor(new DevConsoleMockInterceptor(DevConsole.mockEngine())) .build(); socketClient = new OkHttpClient(); // Mock rules are SESSION-scoped and dropped on every server restart -- restoreRunningSession diff --git a/sdk/api/api/api.api b/sdk/api/api/api.api index 9ecff6e..23936ec 100644 --- a/sdk/api/api/api.api +++ b/sdk/api/api/api.api @@ -7,6 +7,7 @@ public final class io/devconsole/api/AccessInfo { } public final class io/devconsole/api/BindingMode : java/lang/Enum { + public static final field AUTO Lio/devconsole/api/BindingMode; public static final field LAN Lio/devconsole/api/BindingMode; public static final field LOOPBACK Lio/devconsole/api/BindingMode; public static fun getEntries ()Lkotlin/enums/EnumEntries; @@ -15,6 +16,7 @@ public final class io/devconsole/api/BindingMode : java/lang/Enum { } public final class io/devconsole/api/BrowserBinding : java/lang/Enum { + public static final field AUTO Lio/devconsole/api/BrowserBinding; public static final field LAN Lio/devconsole/api/BrowserBinding; public static final field LOOPBACK Lio/devconsole/api/BrowserBinding; public static fun getEntries ()Lkotlin/enums/EnumEntries; diff --git a/sdk/api/src/main/kotlin/io/devconsole/api/DevConsoleConfig.kt b/sdk/api/src/main/kotlin/io/devconsole/api/DevConsoleConfig.kt index 61e31f6..e9f55fd 100644 --- a/sdk/api/src/main/kotlin/io/devconsole/api/DevConsoleConfig.kt +++ b/sdk/api/src/main/kotlin/io/devconsole/api/DevConsoleConfig.kt @@ -42,7 +42,8 @@ data class DevConsoleConfig( var sessionPolicy: SessionPolicy = SessionPolicy() private set - var editingCapabilities: EditingCapabilities = EditingCapabilities.readOnly() + /** Defaults to [EditingCapabilities]'s own defaults -- everything read-only but mocks. */ + var editingCapabilities: EditingCapabilities = EditingCapabilities() private set var retentionPolicy: RetentionPolicy = RetentionPolicy() @@ -201,7 +202,7 @@ data class DevConsoleConfig( private var redactionPolicy: RedactionPolicy = RedactionPolicy.default() private var storagePolicy: StoragePolicy = StoragePolicy() private var sessionPolicy: SessionPolicy = SessionPolicy() - private var editingCapabilities = EditingCapabilities.readOnly() + private var editingCapabilities = EditingCapabilities() private var retentionPolicy: RetentionPolicy? = null private var browserConfig = BrowserConfig() private var crashPolicy = CrashPolicy() diff --git a/sdk/api/src/main/kotlin/io/devconsole/api/EditingCapabilities.kt b/sdk/api/src/main/kotlin/io/devconsole/api/EditingCapabilities.kt index 4501887..6b5cfbe 100644 --- a/sdk/api/src/main/kotlin/io/devconsole/api/EditingCapabilities.kt +++ b/sdk/api/src/main/kotlin/io/devconsole/api/EditingCapabilities.kt @@ -1,11 +1,23 @@ package io.devconsole.api +/** + * Per-surface write permissions for the dashboard and the in-app inspector. + * + * Everything defaults to off except [mocks]. A mock rule writes nothing that belongs to the host -- + * it only short-circuits DevConsole's own OkHttp interceptor -- so the read-only posture that + * protects preferences, databases, and files has nothing to protect here, while a Mocks screen that + * cannot add a mock is the most common "is this thing broken?" first run. Pass `mocks = false`, or + * use [readOnly], to take it back. + * + * Editing mock rules still requires [CaptureCategory.MOCKS] to be enabled; the two gates are + * separate and both must hold. + */ data class EditingCapabilities( val preferences: Boolean = false, val featureFlags: Boolean = false, val database: Boolean = false, val files: Boolean = false, - val mocks: Boolean = false, + val mocks: Boolean = true, val requestExecution: Boolean = false, val captureRules: Boolean = false, ) { @@ -14,7 +26,7 @@ data class EditingCapabilities( private var featureFlags = false private var database = false private var files = false - private var mocks = false + private var mocks = true private var requestExecution = false private var captureRules = false @@ -45,8 +57,22 @@ data class EditingCapabilities( } companion object { + /** + * Grants nothing at all, [mocks] included. Spelled out rather than delegating to the no-arg + * constructor, which now enables mocks -- a host that asks for read-only must get exactly + * that, whatever the defaults drift to later. + */ @JvmStatic - fun readOnly(): EditingCapabilities = EditingCapabilities() + fun readOnly(): EditingCapabilities = + EditingCapabilities( + preferences = false, + featureFlags = false, + database = false, + files = false, + mocks = false, + requestExecution = false, + captureRules = false, + ) @JvmStatic fun builder(): Builder = Builder() diff --git a/sdk/api/src/main/kotlin/io/devconsole/api/FocusedPolicies.kt b/sdk/api/src/main/kotlin/io/devconsole/api/FocusedPolicies.kt index ff03280..763a010 100644 --- a/sdk/api/src/main/kotlin/io/devconsole/api/FocusedPolicies.kt +++ b/sdk/api/src/main/kotlin/io/devconsole/api/FocusedPolicies.kt @@ -16,11 +16,18 @@ private const val DEFAULT_PORT_RANGE_END = 8099 * binds what this field says. Configure this when you want an on-device start to reach the browser * over the network; pass [StartRequest.bindingMode] when your own code is doing the starting. * - * [LOOPBACK] is the default here for the same reason it is on [BindingMode]: the dashboard speaks - * plaintext HTTP, so [LAN] is an explicit decision to expose captured headers, tokens, and bodies to - * anyone who can see the traffic. See the KDoc on [BindingMode] and `docs/THREAT_MODEL.md`. + * [AUTO] is the default here for the same reason it is on [BindingMode]: an on-device Start should + * hand back a URL that works, which means preferring a real network interface and settling for + * loopback when there is none. The dashboard speaks plaintext HTTP, so a start that does reach the + * network exposes captured headers, tokens, and bodies to anyone who can see the traffic; set + * [LOOPBACK] to rule that out, or [LAN] to fail loudly instead of settling. See the KDoc on + * [BindingMode] and `docs/THREAT_MODEL.md`. + * + * Choosing [LAN] here has one practical edge over [AUTO] on this surface: an unpermitted LAN start + * surfaces [StartResult.PermissionRequired] through the More screen's own state polling, which is + * how the inspector prompts for `ACCESS_LOCAL_NETWORK`. [AUTO] binds loopback instead of prompting. */ -enum class BrowserBinding { LOOPBACK, LAN } +enum class BrowserBinding { LOOPBACK, LAN, AUTO } data class RetentionPolicy( val maxSessions: Int = DEFAULT_MAX_SESSIONS, @@ -49,7 +56,7 @@ data class RetentionPolicy( /** SESSION_CODE is the only browser-access flow; there is no longer an access-mode field to set. */ data class BrowserConfig( - val binding: BrowserBinding = BrowserBinding.LOOPBACK, + val binding: BrowserBinding = BrowserBinding.AUTO, val portRange: IntRange = DEFAULT_PORT_RANGE_START..DEFAULT_PORT_RANGE_END, val sessionCodeTtlMs: Long = DEFAULT_SESSION_CODE_TTL_MS, ) { diff --git a/sdk/api/src/main/kotlin/io/devconsole/api/StartRequest.kt b/sdk/api/src/main/kotlin/io/devconsole/api/StartRequest.kt index 9108097..382a539 100644 --- a/sdk/api/src/main/kotlin/io/devconsole/api/StartRequest.kt +++ b/sdk/api/src/main/kotlin/io/devconsole/api/StartRequest.kt @@ -6,24 +6,43 @@ private const val DEFAULT_PORT_RANGE_START = 8080 private const val DEFAULT_PORT_RANGE_END = 8099 /** - * Network exposure requested by the host, passed per-call as [StartRequest.bindingMode]. Loopback - * is the safe default -- the dashboard speaks plaintext HTTP, and `LAN` exposes that traffic to - * anyone else on the local network; see `docs/THREAT_MODEL.md` at the repository root before ever - * passing `LAN`. + * Network exposure requested by the host, passed per-call as [StartRequest.bindingMode]. + * + * [AUTO] is the default: it binds a real network interface when there is one to bind and the + * local-network permission allows it, and quietly binds loopback when either is missing, so a start + * always yields a working server. The dashboard speaks plaintext HTTP, so whenever [AUTO] does + * reach the network it exposes captured headers, tokens, and bodies to anyone who can see that + * traffic -- read `docs/THREAT_MODEL.md` at the repository root and pass [LOOPBACK] explicitly if + * that is not acceptable on the networks you develop on. + * + * [LAN] differs from [AUTO] only in what it does when LAN is unavailable: it fails, returning + * [StartResult.NoEligibleNetwork] or [StartResult.PermissionRequired] rather than degrading. Ask for + * it when a loopback URL would be useless to you -- you are sharing a connect URL or QR code with + * another device -- or when you want [StartResult.PermissionRequired] back so your app can prompt + * for `ACCESS_LOCAL_NETWORK`. Under [AUTO] that permission is never requested on your behalf, so on + * an API 37+ device [AUTO] settles for loopback until something asks for the grant. + * + * [BindingMode.AUTO] never appears on a [BrowserEndpoint]: [BrowserEndpoint.bindingMode] reports the + * mode that actually bound, so it is always [LOOPBACK] or [LAN]. + * + * The name is reused, not restored. A pre-1.0 `BindingMode.AUTO` existed alongside zero-config + * auto-start and NSD service discovery and was removed with them; this one is only a binding + * preference. It discovers nothing, advertises nothing, and starts nothing on its own -- the server + * still starts only when a host calls [io.devconsole.DevConsole.startBrowser] or taps Start. * * This is a distinct type from [BrowserBinding] on [BrowserConfig] (`DevConsoleConfig.browserConfig`), * and the two are **not** layered as "config provides a default, [StartRequest] overrides it". They * answer for different callers: this type decides a start the host issues itself, where the request - * is right there at the call site and defaults to [BindingMode.LOOPBACK] regardless of what any + * is right there at the call site and defaults to [BindingMode.AUTO] regardless of what any * [DevConsoleConfig] says; [BrowserConfig.binding] decides a start the host does not issue -- the * in-app inspector's More-screen Start button, which has no [StartRequest] to carry. Neither reads * the other. See the KDoc on [BrowserBinding] for that side. */ -enum class BindingMode { LOOPBACK, LAN } +enum class BindingMode { LOOPBACK, LAN, AUTO } /** Stable host-facing server start options. */ data class StartRequest( - val bindingMode: BindingMode = BindingMode.LOOPBACK, + val bindingMode: BindingMode = BindingMode.AUTO, val portRange: IntRange = DEFAULT_PORT_RANGE_START..DEFAULT_PORT_RANGE_END, ) { fun validationErrors(): List { diff --git a/sdk/api/src/test/kotlin/io/devconsole/api/DevConsoleContractTest.kt b/sdk/api/src/test/kotlin/io/devconsole/api/DevConsoleContractTest.kt index d97e865..bcc6a04 100644 --- a/sdk/api/src/test/kotlin/io/devconsole/api/DevConsoleContractTest.kt +++ b/sdk/api/src/test/kotlin/io/devconsole/api/DevConsoleContractTest.kt @@ -49,6 +49,18 @@ class DevConsoleContractTest { assertEquals(listOf(ConfigValidationCode.INVALID_PORT_RANGE), errors.map { it.code }) } + /** + * A host that writes no binding mode gets [BindingMode.AUTO], which prefers LAN and degrades to + * loopback rather than failing. [BindingMode.LAN] stays available precisely because it does + * *not* degrade -- see the KDoc on [BindingMode]. + */ + @Test + fun `StartRequest defaults to AUTO binding`() { + assertEquals(BindingMode.AUTO, StartRequest().bindingMode) + assertEquals(BindingMode.LAN, StartRequest(bindingMode = BindingMode.LAN).bindingMode) + assertEquals(BindingMode.LOOPBACK, StartRequest(bindingMode = BindingMode.LOOPBACK).bindingMode) + } + @Test fun `default configuration is valid and uses documented session and storage limits`() { val config = DevConsoleConfig.default() diff --git a/sdk/api/src/test/kotlin/io/devconsole/api/FocusedConfigurationTest.kt b/sdk/api/src/test/kotlin/io/devconsole/api/FocusedConfigurationTest.kt index e4dc19f..a1a33c4 100644 --- a/sdk/api/src/test/kotlin/io/devconsole/api/FocusedConfigurationTest.kt +++ b/sdk/api/src/test/kotlin/io/devconsole/api/FocusedConfigurationTest.kt @@ -6,10 +6,39 @@ import org.junit.Assert.assertTrue import org.junit.Test class FocusedConfigurationTest { + /** + * Mocks are the one editable-by-default surface. They write nothing of the host's -- a mock rule + * only ever short-circuits DevConsole's own interceptor -- so the read-only posture that protects + * preferences, databases, and files buys nothing here, and an empty Mocks screen with a disabled + * "Add rule" button was the single most common "is this broken?" first run. + */ @Test - fun `editing is read only by default`() { + fun `editing is read only by default except for mocks`() { val policy = EditingCapabilities() + assertFalse(policy.preferences) + assertFalse(policy.featureFlags) + assertFalse(policy.database) + assertFalse(policy.files) + assertTrue(policy.mocks) + assertFalse(policy.requestExecution) + assertFalse(policy.captureRules) + } + + @Test + fun `read only opts mocks back out`() { + assertFalse(EditingCapabilities(mocks = false).mocks) + } + + /** + * [EditingCapabilities.readOnly] has to keep meaning what its name says even though the no-arg + * constructor no longer does. A host that asked for read-only and silently got writable mocks + * would be the worst possible reading of this change. + */ + @Test + fun `read only factory grants nothing including mocks`() { + val policy = EditingCapabilities.readOnly() + assertFalse(policy.preferences) assertFalse(policy.featureFlags) assertFalse(policy.database) @@ -19,6 +48,44 @@ class FocusedConfigurationTest { assertFalse(policy.captureRules) } + @Test + fun `java builder starts from the mocks enabled default`() { + assertTrue(EditingCapabilities.builder().build().mocks) + assertFalse( + EditingCapabilities + .builder() + .mocks(false) + .build() + .mocks, + ) + } + + /** + * The capability object's default is only half the story -- [DevConsoleConfig] has to actually + * carry it. It used to seed [EditingCapabilities.readOnly], which still grants nothing, so a + * host that configured no capabilities at all would otherwise keep getting read-only mocks. + */ + @Test + fun `default config makes mocks editable and nothing else`() { + val editing = DevConsoleConfig.default().editingCapabilities + + assertTrue(editing.mocks) + assertFalse(editing.preferences) + assertFalse(editing.database) + assertFalse(editing.files) + assertFalse(editing.captureRules) + } + + @Test + fun `java config builder defaults to editable mocks`() { + assertTrue( + DevConsoleConfig + .builder() + .build() + .editingCapabilities.mocks, + ) + } + @Test fun `java builder enables only requested editing capabilities`() { val policy = @@ -36,17 +103,23 @@ class FocusedConfigurationTest { } @Test - fun `focused policies use persistent sessions and direct loopback defaults`() { + fun `focused policies use persistent sessions and auto binding defaults`() { val retention = RetentionPolicy() val browser = BrowserConfig() assertEquals(10, retention.maxSessions) assertEquals(7L * 24L * 60L * 60L * 1000L, retention.maxAgeMs) assertEquals(100L * 1024L * 1024L, retention.maxBytes) - assertEquals(BrowserBinding.LOOPBACK, browser.binding) + assertEquals(BrowserBinding.AUTO, browser.binding) assertEquals(8080..8099, browser.portRange) } + @Test + fun `browser binding still accepts both explicit modes`() { + assertEquals(BrowserBinding.LOOPBACK, BrowserConfig(binding = BrowserBinding.LOOPBACK).binding) + assertEquals(BrowserBinding.LAN, BrowserConfig(binding = BrowserBinding.LAN).binding) + } + @Test fun `focused policies report every invalid bound`() { val retention = RetentionPolicy(maxSessions = 0, maxAgeMs = 0, maxBytes = 0) diff --git a/sdk/full/src/main/kotlin/io/devconsole/AutoBinding.kt b/sdk/full/src/main/kotlin/io/devconsole/AutoBinding.kt new file mode 100644 index 0000000..de498ce --- /dev/null +++ b/sdk/full/src/main/kotlin/io/devconsole/AutoBinding.kt @@ -0,0 +1,44 @@ +package io.devconsole + +import io.devconsole.server.api.ServerStartResult +import io.devconsole.api.BindingMode as PublicBindingMode +import io.devconsole.server.api.BindingMode as ServerBindingMode + +/** + * Decides what [PublicBindingMode.AUTO] actually binds. + * + * AUTO's promise is that a start always yields a working server: prefer a real network interface, + * settle for loopback when there isn't one. That splits into two questions -- which mode to attempt + * first, and whether a failed attempt is worth retrying on loopback -- and both are pure, so they + * are testable without an API 37+ device or a machine with its interfaces torn down. + * + * [PublicBindingMode.LAN] deliberately routes through neither rescue path. Its whole reason to exist + * next to AUTO is that it fails loudly, so a host sharing a connect URL with another device hears + * about it instead of receiving a `127.0.0.1` link that works for nobody but itself. + */ +internal object AutoBinding { + /** + * The mode to attempt first. AUTO checks [lanPermitted] up front rather than letting an + * unpermitted LAN bind fail and retrying, because that failure has a side effect worth avoiding: + * it would move the runtime through a failed-start transition on the way to a start that + * ultimately succeeds. + */ + fun initialMode( + requested: PublicBindingMode, + lanPermitted: Boolean, + ): ServerBindingMode = + when (requested) { + PublicBindingMode.LOOPBACK -> ServerBindingMode.LOOPBACK + PublicBindingMode.LAN -> ServerBindingMode.LAN + PublicBindingMode.AUTO -> if (lanPermitted) ServerBindingMode.LAN else ServerBindingMode.LOOPBACK + } + + /** + * Whether a failed LAN attempt is one loopback could still serve. Only reachability refusals + * qualify; a port clash or a bad configuration would fail identically on loopback, and retrying + * those would report the same error twice while hiding which bind it came from. + */ + fun rescuableByLoopback(result: ServerStartResult): Boolean = + result is ServerStartResult.NoEligibleNetwork || + result is ServerStartResult.LocalNetworkPermissionRequired +} diff --git a/sdk/full/src/main/kotlin/io/devconsole/PlatformFacadeProvider.kt b/sdk/full/src/main/kotlin/io/devconsole/PlatformFacadeProvider.kt index 4dbec8b..bb44020 100644 --- a/sdk/full/src/main/kotlin/io/devconsole/PlatformFacadeProvider.kt +++ b/sdk/full/src/main/kotlin/io/devconsole/PlatformFacadeProvider.kt @@ -30,6 +30,7 @@ import io.devconsole.core.RuntimeGate import io.devconsole.logs.LogRecorder import io.devconsole.logs.LogSink import io.devconsole.mocks.MockEngine +import io.devconsole.mocks.MockEngineRegistry import io.devconsole.mocks.MockOutcome import io.devconsole.network.InMemoryNetworkTransactionStore import io.devconsole.network.NetworkAttachmentPayload @@ -694,6 +695,11 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { logcatInfo("DevConsole", "Persistent mock rules are unavailable: ${it.javaClass.simpleName}") } } + // Lets `OkHttpClient.Builder.installDevConsole` wire mock rules without the host naming an + // engine -- that module sits below this facade and cannot call mockEngine() itself. Published + // through mockEngine() rather than mockEngineInstance so a host with MOCKS off publishes the + // permanently disabled engine and mocking stays off everywhere, installer included. + MockEngineRegistry.publish(mockEngine()) // Apply the host's policy at the shared capture engine so every recorder redacts by it. redaction.updatePolicy(config.redactionPolicy) if (config.capturesCategory(CaptureCategory.STATE)) { @@ -831,11 +837,11 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { * what [io.devconsole.api.BrowserConfig.binding] is for, and it is now the field that decides: * an on-device start binds what the host asked for, and uses the port range it asked for too. * - * Nothing here loosens the default. [BrowserBinding.LOOPBACK] remains the default on - * [io.devconsole.api.BrowserConfig], so LAN is still reached only by a host that explicitly asks - * for it, and a LAN start still passes through the same [rejectUnpermittedLan] gate as any - * other -- returning [StartResult.PermissionRequired] rather than binding, which the More screen - * surfaces through its normal state polling. + * The default is now [BrowserBinding.AUTO], so an on-device Start reaches the network whenever + * the device has one to reach and falls back to loopback when it does not. An explicit + * [BrowserBinding.LAN] still passes through the [rejectUnpermittedLan] gate -- returning + * [StartResult.PermissionRequired] rather than binding, which the More screen surfaces through + * its normal state polling, and which is the only way this surface prompts for the permission. */ private fun configuredStartRequest(): StartRequest { val browser = activeConfig?.browserConfig ?: return StartRequest() @@ -844,6 +850,7 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { when (browser.binding) { BrowserBinding.LOOPBACK -> PublicBindingMode.LOOPBACK BrowserBinding.LAN -> PublicBindingMode.LAN + BrowserBinding.AUTO -> PublicBindingMode.AUTO }, portRange = browser.portRange, ) @@ -1004,7 +1011,8 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { runtime.serverFailed("Durable app-run session is unavailable") return@withContext StartResult.Failed("Durable app-run session is unavailable") } - rejectUnpermittedLan(application, runtime, request)?.let { return@withContext it } + val lanPermitted = localNetworkPermitted(application) + rejectUnpermittedLan(runtime, request, lanPermitted)?.let { return@withContext it } withContext(Dispatchers.IO) { runCatching { val history = @@ -1025,20 +1033,32 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { val activeEngine = synchronized(this@PlatformFacadeProvider) { serverEngine } val browserConfig = activeConfig?.browserConfig - val serverRequest = + val sessionCodeTtlMs = + browserConfig?.sessionCodeTtlMs ?: SessionCodeAuthority.DEFAULT_SESSION_CODE_TTL_MS + + fun serverRequest(mode: ServerBindingMode) = ServerStartRequest( - bindingMode = - when (request.bindingMode) { - PublicBindingMode.LOOPBACK -> ServerBindingMode.LOOPBACK - PublicBindingMode.LAN -> ServerBindingMode.LAN - }, + bindingMode = mode, portRange = request.portRange, - sessionCodeTtlMs = - browserConfig?.sessionCodeTtlMs ?: SessionCodeAuthority.DEFAULT_SESSION_CODE_TTL_MS, + sessionCodeTtlMs = sessionCodeTtlMs, ) // The engine's bind loop does blocking socket probes (Thread.sleep per port); keep it off // the caller's dispatcher so a host doing `lifecycleScope.launch { startBrowser() }` on Main never ANRs. - val result = withContext(Dispatchers.IO) { activeEngine.start(serverRequest) } + val attempted = AutoBinding.initialMode(request.bindingMode, lanPermitted) + val attempt = withContext(Dispatchers.IO) { activeEngine.start(serverRequest(attempted)) } + // Only AUTO retries. The first attempt is left unmapped until the retry is settled so a + // rescued start never drags the runtime through serverFailed() on its way to serverStarted(). + val rescue = + request.bindingMode == PublicBindingMode.AUTO && + attempted == ServerBindingMode.LAN && + AutoBinding.rescuableByLoopback(attempt) + val result = + if (rescue) { + logcatInfo("DevConsole", "LAN is unavailable ($attempt); binding loopback instead") + withContext(Dispatchers.IO) { activeEngine.start(serverRequest(ServerBindingMode.LOOPBACK)) } + } else { + attempt + } mapStartResult(result) } } @@ -1439,13 +1459,14 @@ private const val CURSOR_SECRET_BYTES = 16 private fun randomCursorSecret(): ByteArray = ByteArray(CURSOR_SECRET_BYTES).also(SecureRandom()::nextBytes) -/** Null means LAN binding may proceed; a non-null result is the early-return for [PlatformFacadeProvider.start]. */ -private fun rejectUnpermittedLan( - application: Application, - runtime: DevConsoleRuntime, - request: StartRequest, -): StartResult? { - if (request.bindingMode != PublicBindingMode.LAN) return null +/** + * Whether a LAN bind would be allowed to reach the network right now. + * + * Below API 37 this is always true. At or above it, an ungranted `ACCESS_LOCAL_NETWORK` means the + * platform silently drops LAN traffic even though the socket binds and completes handshakes -- see + * [LocalNetworkPermissionGate], which deliberately ignores `targetSdk` for that reason. + */ +private fun localNetworkPermitted(application: Application): Boolean { val isGranted = application.checkSelfPermission(LocalNetworkPermissionGate.PERMISSION) == PackageManager.PERMISSION_GRANTED val decision = @@ -1455,10 +1476,26 @@ private fun rejectUnpermittedLan( targetSdk = application.applicationInfo.targetSdkVersion, isGranted = isGranted, ) - return (decision as? LocalNetworkPermissionDecision.PermissionRequired)?.let { - runtime.serverRequiresPermission() - StartResult.PermissionRequired(it.permission) - } + return decision !is LocalNetworkPermissionDecision.PermissionRequired +} + +/** + * Null means the start may proceed; a non-null result is the early-return for + * [PlatformFacadeProvider.start]. + * + * Only an explicit [PublicBindingMode.LAN] is rejected here. [PublicBindingMode.AUTO] treats a + * missing grant as a reason to bind loopback rather than a reason to fail, so it never reaches this + * function -- which also means AUTO never surfaces [StartResult.PermissionRequired] and never gives + * a host the cue to prompt for the permission. Hosts that want the prompt ask for LAN by name. + */ +private fun rejectUnpermittedLan( + runtime: DevConsoleRuntime, + request: StartRequest, + lanPermitted: Boolean, +): StartResult? { + if (request.bindingMode != PublicBindingMode.LAN || lanPermitted) return null + runtime.serverRequiresPermission() + return StartResult.PermissionRequired(LocalNetworkPermissionGate.PERMISSION) } private fun Application.serverMetadata(): ServerMetadata { diff --git a/sdk/full/src/test/kotlin/io/devconsole/AutoBindingTest.kt b/sdk/full/src/test/kotlin/io/devconsole/AutoBindingTest.kt new file mode 100644 index 0000000..7067753 --- /dev/null +++ b/sdk/full/src/test/kotlin/io/devconsole/AutoBindingTest.kt @@ -0,0 +1,55 @@ +package io.devconsole + +import io.devconsole.api.BindingMode +import io.devconsole.server.api.ServerStartResult +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test +import io.devconsole.server.api.BindingMode as ServerBindingMode + +/** + * The policy half of [BindingMode.AUTO], kept as pure functions so both halves are testable without + * a device: the real fallback needs an API 37+ runtime with the permission withheld, or a device + * with every network interface down, neither of which Robolectric can stage. The wiring half -- that + * `startLocked` actually consults these -- is covered by `PlatformFacadeProviderAutoBindingTest`. + */ +class AutoBindingTest { + @Test + fun `auto attempts LAN when the local network permission is granted`() { + assertEquals(ServerBindingMode.LAN, AutoBinding.initialMode(BindingMode.AUTO, lanPermitted = true)) + } + + /** + * The distinguishing case. An unpermitted LAN bind is refused by the platform, and AUTO must not + * spend a failed start discovering that -- it goes straight to loopback, which needs no grant. + */ + @Test + fun `auto goes straight to loopback when the local network permission is missing`() { + assertEquals(ServerBindingMode.LOOPBACK, AutoBinding.initialMode(BindingMode.AUTO, lanPermitted = false)) + } + + @Test + fun `explicit modes ignore the permission state and bind what was asked`() { + assertEquals(ServerBindingMode.LAN, AutoBinding.initialMode(BindingMode.LAN, lanPermitted = false)) + assertEquals(ServerBindingMode.LOOPBACK, AutoBinding.initialMode(BindingMode.LOOPBACK, lanPermitted = true)) + } + + @Test + fun `a LAN attempt with no eligible network is rescuable by loopback`() { + assertTrue(AutoBinding.rescuableByLoopback(ServerStartResult.NoEligibleNetwork("airplane mode"))) + assertTrue(AutoBinding.rescuableByLoopback(ServerStartResult.LocalNetworkPermissionRequired)) + } + + /** + * Everything else is a genuine failure that loopback would hit too, so retrying would turn one + * honest error into two. A port clash is the sharp case: the range is the same either way. + */ + @Test + fun `failures loopback cannot rescue are left alone`() { + assertFalse(AutoBinding.rescuableByLoopback(ServerStartResult.PortUnavailable(8080..8099))) + assertFalse(AutoBinding.rescuableByLoopback(ServerStartResult.Failed("boom"))) + assertFalse(AutoBinding.rescuableByLoopback(ServerStartResult.InvalidConfiguration("bad range"))) + assertFalse(AutoBinding.rescuableByLoopback(ServerStartResult.DisabledForBuild)) + } +} diff --git a/sdk/full/src/test/kotlin/io/devconsole/FullFacadeTest.kt b/sdk/full/src/test/kotlin/io/devconsole/FullFacadeTest.kt index 21b9690..7d59bfd 100644 --- a/sdk/full/src/test/kotlin/io/devconsole/FullFacadeTest.kt +++ b/sdk/full/src/test/kotlin/io/devconsole/FullFacadeTest.kt @@ -96,7 +96,9 @@ class FullFacadeTest { val started = provider.startBrowser(StartRequest()) assertTrue(started is StartResult.Started) started as StartResult.Started - assertEquals(BindingMode.LOOPBACK, started.endpoint.bindingMode) + // A bare StartRequest() is BindingMode.AUTO, and Robolectric presents an eligible + // interface, so the default start reaches the network. See PlatformFacadeProviderAutoBindingTest. + assertEquals(BindingMode.LAN, started.endpoint.bindingMode) assertTrue(started.endpoint.port in 8080..8099) assertTrue(started.access.connectUrl.contains("#code=")) assertEquals(DevConsoleState.Running, provider.state().value) diff --git a/sdk/full/src/test/kotlin/io/devconsole/MockEnginePublishingTest.kt b/sdk/full/src/test/kotlin/io/devconsole/MockEnginePublishingTest.kt new file mode 100644 index 0000000..a76b0eb --- /dev/null +++ b/sdk/full/src/test/kotlin/io/devconsole/MockEnginePublishingTest.kt @@ -0,0 +1,60 @@ +package io.devconsole + +import androidx.test.core.app.ApplicationProvider +import io.devconsole.api.CaptureCategory +import io.devconsole.api.DevConsoleConfig +import io.devconsole.mocks.MockDecision +import io.devconsole.mocks.MockEngineRegistry +import io.devconsole.mocks.MockRequest +import org.junit.After +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +/** + * `installDevConsole` wires mock rules from whatever engine is in [MockEngineRegistry], which is only + * useful if the enabled facade actually puts one there. Without this, the default mock setup would + * silently do nothing: the installer would read `null` on every host and quietly skip the + * interceptor, exactly the inert Mocks screen the default exists to fix. + */ +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34]) +class MockEnginePublishingTest { + @After fun tearDown() = MockEngineRegistry.clear() + + @Test + fun `initialize publishes the facade's own engine`() { + MockEngineRegistry.clear() + val provider = PlatformFacadeProvider() + + provider.initialize(ApplicationProvider.getApplicationContext(), DevConsoleConfig.default()) + + assertSame(provider.mockEngine(), MockEngineRegistry.active()) + } + + /** + * A host that turned [CaptureCategory.MOCKS] off must not get mocking wired in through the back + * door. `mockEngine()` already answers with a permanently disabled engine in that case, so + * publishing its result -- rather than the live instance -- is what keeps the gate honest. + */ + @Test + fun `the published engine respects a disabled MOCKS category`() { + MockEngineRegistry.clear() + val provider = PlatformFacadeProvider() + + provider.initialize( + ApplicationProvider.getApplicationContext(), + DevConsoleConfig.default().withCaptureCategories(CaptureCategory.all() - CaptureCategory.MOCKS), + ) + + val published = MockEngineRegistry.active() + assertSame(provider.mockEngine(), published) + assertTrue( + "a disabled engine must pass every request through", + published?.decide(MockRequest("GET", "https", "api.test", "/orders")) is MockDecision.Passthrough, + ) + } +} diff --git a/sdk/full/src/test/kotlin/io/devconsole/PlatformFacadeProviderAutoBindingTest.kt b/sdk/full/src/test/kotlin/io/devconsole/PlatformFacadeProviderAutoBindingTest.kt new file mode 100644 index 0000000..0a70d2a --- /dev/null +++ b/sdk/full/src/test/kotlin/io/devconsole/PlatformFacadeProviderAutoBindingTest.kt @@ -0,0 +1,78 @@ +package io.devconsole + +import androidx.test.core.app.ApplicationProvider +import io.devconsole.api.BindingMode +import io.devconsole.api.DevConsoleConfig +import io.devconsole.api.StartRequest +import io.devconsole.api.StartResult +import io.devconsole.api.StopReason +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +/** + * The wiring half of [BindingMode.AUTO]: that `startLocked` consults [AutoBinding] at all, and that + * a bare `StartRequest()` -- the shape most hosts write -- reaches the network. + * + * Only the LAN-available branch is reachable here. Robolectric always presents an eligible interface + * and reports API 34, below the API 37 line where `ACCESS_LOCAL_NETWORK` starts being enforced, so + * the two fallback branches cannot be staged in this runner; [AutoBindingTest] covers that decision + * directly instead. + */ +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34]) +class PlatformFacadeProviderAutoBindingTest { + @Test + fun `a default start request binds LAN when the device has a network`() = + runTest { + val provider = PlatformFacadeProvider() + provider.initialize(ApplicationProvider.getApplicationContext(), DevConsoleConfig.default()) + + val started = provider.startBrowser(StartRequest(portRange = 8660..8679)) as StartResult.Started + assertEquals(BindingMode.LAN, started.endpoint.bindingMode) + + provider.stop(StopReason.UserRequested) + } + + /** + * AUTO resolves to a concrete socket, so it must never survive into the endpoint the host reads + * back -- the connect URL, the QR code, and the "LAN MODE — UNENCRYPTED" banner all key off this + * field and would be lying if it said AUTO. + */ + @Test + fun `AUTO never surfaces as the bound mode`() = + runTest { + val provider = PlatformFacadeProvider() + provider.initialize(ApplicationProvider.getApplicationContext(), DevConsoleConfig.default()) + + val started = + provider.startBrowser( + StartRequest(bindingMode = BindingMode.AUTO, portRange = 8680..8699), + ) as StartResult.Started + + assertTrue(started.endpoint.bindingMode in setOf(BindingMode.LOOPBACK, BindingMode.LAN)) + + provider.stop(StopReason.UserRequested) + } + + @Test + fun `an explicit loopback request is untouched by AUTO handling`() = + runTest { + val provider = PlatformFacadeProvider() + provider.initialize(ApplicationProvider.getApplicationContext(), DevConsoleConfig.default()) + + val started = + provider.startBrowser( + StartRequest(bindingMode = BindingMode.LOOPBACK, portRange = 8700..8719), + ) as StartResult.Started + + assertEquals(BindingMode.LOOPBACK, started.endpoint.bindingMode) + assertEquals("127.0.0.1", started.endpoint.host) + + provider.stop(StopReason.UserRequested) + } +} diff --git a/sdk/full/src/test/kotlin/io/devconsole/PlatformFacadeProviderMoreScreenBindingTest.kt b/sdk/full/src/test/kotlin/io/devconsole/PlatformFacadeProviderMoreScreenBindingTest.kt index bdc6097..a5f3f28 100644 --- a/sdk/full/src/test/kotlin/io/devconsole/PlatformFacadeProviderMoreScreenBindingTest.kt +++ b/sdk/full/src/test/kotlin/io/devconsole/PlatformFacadeProviderMoreScreenBindingTest.kt @@ -29,8 +29,10 @@ import org.robolectric.annotation.Config * always bound loopback, which meant a host configured for LAN still got a `127.0.0.1` connect URL * whenever the start came from the device rather than from its own code. * - * Both directions are asserted: the default config must still bind loopback (the safe default is the - * whole reason LAN is opt-in), and a LAN-configured host must actually reach LAN. + * All three bindings are asserted. The default is [BrowserBinding.AUTO], which on a device with a + * live interface -- Robolectric gives us one -- means the on-device Start reaches the network + * without the host configuring anything. A [BrowserBinding.LOOPBACK] host must still be held to + * `127.0.0.1`, since that is now the only way to rule the network out. */ @RunWith(RobolectricTestRunner::class) @Config(sdk = [34]) @@ -52,11 +54,27 @@ class PlatformFacadeProviderMoreScreenBindingTest { } @Test - fun `More screen start still binds loopback under the default config`() = + fun `More screen start reaches LAN under the default config`() = runTest { val provider = PlatformFacadeProvider() provider.initialize(ApplicationProvider.getApplicationContext(), DevConsoleConfig.default()) + assertEquals(BindingMode.LAN, provider.startFromMoreScreen().bindingMode) + + provider.stop(StopReason.UserRequested) + } + + @Test + fun `More screen start binds loopback when the host configured LOOPBACK`() = + runTest { + val provider = PlatformFacadeProvider() + provider.initialize( + ApplicationProvider.getApplicationContext(), + DevConsoleConfig.default().withBrowserConfig( + BrowserConfig(binding = BrowserBinding.LOOPBACK, portRange = 8640..8659), + ), + ) + assertEquals(BindingMode.LOOPBACK, provider.startFromMoreScreen().bindingMode) provider.stop(StopReason.UserRequested) diff --git a/sdk/mocks-okhttp/src/main/kotlin/io/devconsole/mocks/okhttp/DevConsoleMockInterceptor.kt b/sdk/mocks-okhttp/src/main/kotlin/io/devconsole/mocks/okhttp/DevConsoleMockInterceptor.kt index ffbe8ac..b70907b 100644 --- a/sdk/mocks-okhttp/src/main/kotlin/io/devconsole/mocks/okhttp/DevConsoleMockInterceptor.kt +++ b/sdk/mocks-okhttp/src/main/kotlin/io/devconsole/mocks/okhttp/DevConsoleMockInterceptor.kt @@ -18,6 +18,13 @@ class DevConsoleMockInterceptor( ) : Interceptor { override fun intercept(chain: Interceptor.Chain): Response { val request = chain.request() + // `installDevConsole` wires one of these by default, so a host that also kept its own manual + // `.addInterceptor(DevConsoleMockInterceptor(...))` line now has two in the chain. Deciding + // twice is not merely redundant: a Delay rule would sleep in both passes, silently doubling + // every simulated latency the moment the host upgraded. Whoever got there first owns the call. + if (request.tag(NetworkCaptureContext::class.java)?.tags?.containsKey("mocked") == true) { + return chain.proceed(request) + } val decision = engine.decide( MockRequest( diff --git a/sdk/mocks/api/mocks.api b/sdk/mocks/api/mocks.api index 1831eea..c5eb81a 100644 --- a/sdk/mocks/api/mocks.api +++ b/sdk/mocks/api/mocks.api @@ -157,6 +157,13 @@ public final class io/devconsole/mocks/MockEngine { public final fun withOutcomeSink (Lio/devconsole/mocks/MockOutcomeSink;)Lio/devconsole/mocks/MockEngine; } +public final class io/devconsole/mocks/MockEngineRegistry { + public static final field INSTANCE Lio/devconsole/mocks/MockEngineRegistry; + public final fun active ()Lio/devconsole/mocks/MockEngine; + public final fun clear ()V + public final fun publish (Lio/devconsole/mocks/MockEngine;)V +} + public abstract interface class io/devconsole/mocks/MockOutcome { } diff --git a/sdk/mocks/src/main/kotlin/io/devconsole/mocks/MockEngineRegistry.kt b/sdk/mocks/src/main/kotlin/io/devconsole/mocks/MockEngineRegistry.kt new file mode 100644 index 0000000..7c074fc --- /dev/null +++ b/sdk/mocks/src/main/kotlin/io/devconsole/mocks/MockEngineRegistry.kt @@ -0,0 +1,32 @@ +package io.devconsole.mocks + +/** + * Process-wide handle on the [MockEngine] the running DevConsole owns. + * + * This exists to close a module-layering gap, not to be a general service locator. The one-call + * OkHttp installer lives in `:sdk:network-okhttp`, which sits below the facade and so cannot call + * `DevConsole.mockEngine()`; without a handle it could only wire mocking if the host passed the + * engine in by hand, which is exactly the extra line the default is meant to remove. The enabled + * facade publishes its engine here at initialize and the installer reads it back. + * + * The protected (no-op) facade publishes nothing, so a release build reads `null` and the no-op + * installer wires no mock interceptor at all. + * + * Hosts do not call this. Pass a [MockEngine] to the installer explicitly if you want to bypass it. + */ +object MockEngineRegistry { + @Volatile + private var engine: MockEngine? = null + + /** Replaces whatever was published before -- `initialize` may be called more than once. */ + fun publish(engine: MockEngine) { + this.engine = engine + } + + /** Null before `DevConsole.initialize` succeeds, and on a protected build. */ + fun active(): MockEngine? = engine + + fun clear() { + engine = null + } +} diff --git a/sdk/mocks/src/test/kotlin/io/devconsole/mocks/MockEngineRegistryTest.kt b/sdk/mocks/src/test/kotlin/io/devconsole/mocks/MockEngineRegistryTest.kt new file mode 100644 index 0000000..caf59ef --- /dev/null +++ b/sdk/mocks/src/test/kotlin/io/devconsole/mocks/MockEngineRegistryTest.kt @@ -0,0 +1,55 @@ +package io.devconsole.mocks + +import org.junit.After +import org.junit.Assert.assertNull +import org.junit.Assert.assertSame +import org.junit.Test + +/** + * The registry exists so `installDevConsole` can wire mocking without the host naming an engine. + * `:sdk:network-okhttp` sits below the facade and cannot call `DevConsole.mockEngine()`; the enabled + * facade publishes here at initialize instead, and the installer reads it back. + * + * Deliberately process-wide, which is the same lifetime `DevConsole` itself already has: one engine + * per app, created once at initialize. + */ +class MockEngineRegistryTest { + @After fun tearDown() = MockEngineRegistry.clear() + + @Test fun `no engine is active until one is published`() { + MockEngineRegistry.clear() + + assertNull(MockEngineRegistry.active()) + } + + @Test fun `the published engine is what callers read back`() { + val engine = MockEngine(listOf(MockRule("rule", 1, path = "/orders"))) + + MockEngineRegistry.publish(engine) + + assertSame(engine, MockEngineRegistry.active()) + } + + /** + * `initialize` is documented as re-callable, so a second publish has to win outright. Leaving the + * first engine in place would point every OkHttp client built afterwards at rules the dashboard + * is no longer writing to. + */ + @Test fun `a later publish replaces the engine wholesale`() { + val first = MockEngine(listOf(MockRule("first", 1, path = "/a"))) + val second = MockEngine(listOf(MockRule("second", 1, path = "/b"))) + + MockEngineRegistry.publish(first) + MockEngineRegistry.publish(second) + + assertSame(second, MockEngineRegistry.active()) + } + + @Test fun `clearing drops the engine`() { + MockEngineRegistry.publish(MockEngine(listOf(MockRule("rule", 1, path = "/orders")))) + + MockEngineRegistry.clear() + + assertNull(MockEngineRegistry.active()) + } +} diff --git a/sdk/network-okhttp-noop/api/network-okhttp-noop.api b/sdk/network-okhttp-noop/api/network-okhttp-noop.api index 11b7bd5..943bb0a 100644 --- a/sdk/network-okhttp-noop/api/network-okhttp-noop.api +++ b/sdk/network-okhttp-noop/api/network-okhttp-noop.api @@ -2,7 +2,8 @@ public final class io/devconsole/network/okhttp/DevConsoleOkHttp { public static final field INSTANCE Lio/devconsole/network/okhttp/DevConsoleOkHttp; public static final fun install (Lokhttp3/OkHttpClient$Builder;Lio/devconsole/network/NetworkTransactionRecorder;)Lokhttp3/OkHttpClient$Builder; public static final fun install (Lokhttp3/OkHttpClient$Builder;Lio/devconsole/network/NetworkTransactionRecorder;Lokhttp3/EventListener$Factory;)Lokhttp3/OkHttpClient$Builder; - public static synthetic fun install$default (Lokhttp3/OkHttpClient$Builder;Lio/devconsole/network/NetworkTransactionRecorder;Lokhttp3/EventListener$Factory;ILjava/lang/Object;)Lokhttp3/OkHttpClient$Builder; + public static final fun install (Lokhttp3/OkHttpClient$Builder;Lio/devconsole/network/NetworkTransactionRecorder;Lokhttp3/EventListener$Factory;Lio/devconsole/mocks/MockEngine;)Lokhttp3/OkHttpClient$Builder; + public static synthetic fun install$default (Lokhttp3/OkHttpClient$Builder;Lio/devconsole/network/NetworkTransactionRecorder;Lokhttp3/EventListener$Factory;Lio/devconsole/mocks/MockEngine;ILjava/lang/Object;)Lokhttp3/OkHttpClient$Builder; } public final class io/devconsole/network/okhttp/DevConsoleOkHttpEventListenerFactory : okhttp3/EventListener$Factory { @@ -22,6 +23,7 @@ public final class io/devconsole/network/okhttp/DevConsoleOkHttpInterceptor : ok public final class io/devconsole/network/okhttp/DevConsoleOkHttpKt { public static final fun installDevConsole (Lokhttp3/OkHttpClient$Builder;Lio/devconsole/network/NetworkTransactionRecorder;)Lokhttp3/OkHttpClient$Builder; public static final fun installDevConsole (Lokhttp3/OkHttpClient$Builder;Lio/devconsole/network/NetworkTransactionRecorder;Lokhttp3/EventListener$Factory;)Lokhttp3/OkHttpClient$Builder; - public static synthetic fun installDevConsole$default (Lokhttp3/OkHttpClient$Builder;Lio/devconsole/network/NetworkTransactionRecorder;Lokhttp3/EventListener$Factory;ILjava/lang/Object;)Lokhttp3/OkHttpClient$Builder; + public static final fun installDevConsole (Lokhttp3/OkHttpClient$Builder;Lio/devconsole/network/NetworkTransactionRecorder;Lokhttp3/EventListener$Factory;Lio/devconsole/mocks/MockEngine;)Lokhttp3/OkHttpClient$Builder; + public static synthetic fun installDevConsole$default (Lokhttp3/OkHttpClient$Builder;Lio/devconsole/network/NetworkTransactionRecorder;Lokhttp3/EventListener$Factory;Lio/devconsole/mocks/MockEngine;ILjava/lang/Object;)Lokhttp3/OkHttpClient$Builder; } diff --git a/sdk/network-okhttp-noop/build.gradle.kts b/sdk/network-okhttp-noop/build.gradle.kts index 638aa3f..fcfa0df 100644 --- a/sdk/network-okhttp-noop/build.gradle.kts +++ b/sdk/network-okhttp-noop/build.gradle.kts @@ -8,6 +8,9 @@ android { namespace = "io.devconsole.network.okhttp.noop" } dependencies { implementation(project(":sdk:network")) + // Mirrors the enabled module: MockEngine is named in installDevConsole's signature on both sides, + // so it has to be visible to consumers here too or the release variant would not compile. + api(project(":sdk:mocks")) implementation("com.squareup.okhttp3:okhttp:4.12.0") testImplementation("com.squareup.okhttp3:mockwebserver:4.12.0") } diff --git a/sdk/network-okhttp-noop/src/main/kotlin/io/devconsole/network/okhttp/DevConsoleOkHttp.kt b/sdk/network-okhttp-noop/src/main/kotlin/io/devconsole/network/okhttp/DevConsoleOkHttp.kt index f1a994c..268bd3b 100644 --- a/sdk/network-okhttp-noop/src/main/kotlin/io/devconsole/network/okhttp/DevConsoleOkHttp.kt +++ b/sdk/network-okhttp-noop/src/main/kotlin/io/devconsole/network/okhttp/DevConsoleOkHttp.kt @@ -4,6 +4,8 @@ */ package io.devconsole.network.okhttp +import io.devconsole.mocks.MockEngine +import io.devconsole.mocks.MockEngineRegistry import io.devconsole.network.NetworkTransactionRecorder import okhttp3.EventListener import okhttp3.OkHttpClient @@ -13,11 +15,17 @@ import okhttp3.OkHttpClient * host call sites compile unchanged across variants, but wires only no-op components -- the * resulting listener factory forwards to [existingEventListenerFactory] without allocating capture * state, and the interceptor added alongside it never inspects or records the call. + * + * [mockEngine] is accepted and discarded. Its default reads [MockEngineRegistry], which nothing + * populates on a protected build -- the no-op facade publishes no engine -- so it resolves to `null` + * anyway; taking the parameter at all is purely so a host that passes one explicitly still compiles + * in release. No mock interceptor is ever added here, and no rule can alter release traffic. */ @JvmOverloads fun OkHttpClient.Builder.installDevConsole( recorder: NetworkTransactionRecorder, existingEventListenerFactory: EventListener.Factory? = null, + @Suppress("UNUSED_PARAMETER") mockEngine: MockEngine? = MockEngineRegistry.active(), ): OkHttpClient.Builder { val listenerFactory = DevConsoleOkHttpEventListenerFactory(existingEventListenerFactory) return eventListenerFactory(listenerFactory) @@ -32,5 +40,6 @@ object DevConsoleOkHttp { builder: OkHttpClient.Builder, recorder: NetworkTransactionRecorder, existingEventListenerFactory: EventListener.Factory? = null, - ): OkHttpClient.Builder = builder.installDevConsole(recorder, existingEventListenerFactory) + mockEngine: MockEngine? = MockEngineRegistry.active(), + ): OkHttpClient.Builder = builder.installDevConsole(recorder, existingEventListenerFactory, mockEngine) } diff --git a/sdk/network-okhttp/api/network-okhttp.api b/sdk/network-okhttp/api/network-okhttp.api index 4699e69..e8e6e7e 100644 --- a/sdk/network-okhttp/api/network-okhttp.api +++ b/sdk/network-okhttp/api/network-okhttp.api @@ -2,7 +2,8 @@ public final class io/devconsole/network/okhttp/DevConsoleOkHttp { public static final field INSTANCE Lio/devconsole/network/okhttp/DevConsoleOkHttp; public static final fun install (Lokhttp3/OkHttpClient$Builder;Lio/devconsole/network/NetworkTransactionRecorder;)Lokhttp3/OkHttpClient$Builder; public static final fun install (Lokhttp3/OkHttpClient$Builder;Lio/devconsole/network/NetworkTransactionRecorder;Lokhttp3/EventListener$Factory;)Lokhttp3/OkHttpClient$Builder; - public static synthetic fun install$default (Lokhttp3/OkHttpClient$Builder;Lio/devconsole/network/NetworkTransactionRecorder;Lokhttp3/EventListener$Factory;ILjava/lang/Object;)Lokhttp3/OkHttpClient$Builder; + public static final fun install (Lokhttp3/OkHttpClient$Builder;Lio/devconsole/network/NetworkTransactionRecorder;Lokhttp3/EventListener$Factory;Lio/devconsole/mocks/MockEngine;)Lokhttp3/OkHttpClient$Builder; + public static synthetic fun install$default (Lokhttp3/OkHttpClient$Builder;Lio/devconsole/network/NetworkTransactionRecorder;Lokhttp3/EventListener$Factory;Lio/devconsole/mocks/MockEngine;ILjava/lang/Object;)Lokhttp3/OkHttpClient$Builder; } public final class io/devconsole/network/okhttp/DevConsoleOkHttpEventListenerFactory : okhttp3/EventListener$Factory { @@ -24,6 +25,7 @@ public final class io/devconsole/network/okhttp/DevConsoleOkHttpInterceptor : ok public final class io/devconsole/network/okhttp/DevConsoleOkHttpKt { public static final fun installDevConsole (Lokhttp3/OkHttpClient$Builder;Lio/devconsole/network/NetworkTransactionRecorder;)Lokhttp3/OkHttpClient$Builder; public static final fun installDevConsole (Lokhttp3/OkHttpClient$Builder;Lio/devconsole/network/NetworkTransactionRecorder;Lokhttp3/EventListener$Factory;)Lokhttp3/OkHttpClient$Builder; - public static synthetic fun installDevConsole$default (Lokhttp3/OkHttpClient$Builder;Lio/devconsole/network/NetworkTransactionRecorder;Lokhttp3/EventListener$Factory;ILjava/lang/Object;)Lokhttp3/OkHttpClient$Builder; + public static final fun installDevConsole (Lokhttp3/OkHttpClient$Builder;Lio/devconsole/network/NetworkTransactionRecorder;Lokhttp3/EventListener$Factory;Lio/devconsole/mocks/MockEngine;)Lokhttp3/OkHttpClient$Builder; + public static synthetic fun installDevConsole$default (Lokhttp3/OkHttpClient$Builder;Lio/devconsole/network/NetworkTransactionRecorder;Lokhttp3/EventListener$Factory;Lio/devconsole/mocks/MockEngine;ILjava/lang/Object;)Lokhttp3/OkHttpClient$Builder; } diff --git a/sdk/network-okhttp/build.gradle.kts b/sdk/network-okhttp/build.gradle.kts index 2f17dda..b9a126b 100644 --- a/sdk/network-okhttp/build.gradle.kts +++ b/sdk/network-okhttp/build.gradle.kts @@ -11,6 +11,10 @@ android { dependencies { implementation(project(":sdk:network")) + // `api`, not `implementation`: MockEngine is named in installDevConsole's own signature (as the + // type of its defaulted mockEngine parameter), so a consumer cannot resolve the call without it. + api(project(":sdk:mocks")) + implementation(project(":sdk:mocks-okhttp")) implementation("com.squareup.okhttp3:okhttp:4.12.0") testImplementation("com.squareup.okhttp3:mockwebserver:4.12.0") } diff --git a/sdk/network-okhttp/src/main/kotlin/io/devconsole/network/okhttp/DevConsoleOkHttp.kt b/sdk/network-okhttp/src/main/kotlin/io/devconsole/network/okhttp/DevConsoleOkHttp.kt index 99cce28..b045223 100644 --- a/sdk/network-okhttp/src/main/kotlin/io/devconsole/network/okhttp/DevConsoleOkHttp.kt +++ b/sdk/network-okhttp/src/main/kotlin/io/devconsole/network/okhttp/DevConsoleOkHttp.kt @@ -4,6 +4,9 @@ */ package io.devconsole.network.okhttp +import io.devconsole.mocks.MockEngine +import io.devconsole.mocks.MockEngineRegistry +import io.devconsole.mocks.okhttp.DevConsoleMockInterceptor import io.devconsole.network.NetworkTransactionRecorder import okhttp3.EventListener import okhttp3.OkHttpClient @@ -36,6 +39,17 @@ import okhttp3.OkHttpClient * the network has no phases at all. That is by design, not a sign the installer is missing * something. * + * **Mock rules come with it.** [mockEngine] defaults to whatever engine the running DevConsole + * published to [MockEngineRegistry], so the dashboard's Mocks screen works off this one call and the + * separate `.addInterceptor(DevConsoleMockInterceptor(DevConsole.mockEngine()))` line is no longer + * needed -- keeping it is harmless, since a second interceptor recognises the first and stands down. + * Nothing changes for traffic until a rule matches: with no rules, or before `DevConsole.initialize` + * has published an engine, every call passes straight through. Pass an explicit engine to mock + * against something other than the live one, or `null` to install no mock interceptor at all. + * + * The mock interceptor is added *after* the capture interceptor, which is what keeps a served mock + * visible in the network inspector (tagged `mocked`) rather than invisible to it. + * * The manual three-step form documented on [DevConsoleOkHttpEventListenerFactory] remains available * and fully supported for callers who want to manage the interceptor and event listener lifecycles * separately. @@ -44,18 +58,20 @@ import okhttp3.OkHttpClient fun OkHttpClient.Builder.installDevConsole( recorder: NetworkTransactionRecorder, existingEventListenerFactory: EventListener.Factory? = null, + mockEngine: MockEngine? = MockEngineRegistry.active(), ): OkHttpClient.Builder { val listenerFactory = DevConsoleOkHttpEventListenerFactory(existingEventListenerFactory) return eventListenerFactory(listenerFactory) .addInterceptor(DevConsoleOkHttpInterceptor(recorder, listenerFactory)) + .apply { mockEngine?.let { addInterceptor(DevConsoleMockInterceptor(it)) } } } /** * Java-friendly mirror of [installDevConsole]. Kotlin extension functions are not callable as - * instance methods from Java, so this object gives Java hosts the same one-call installer: + * instance methods from Java, so this object gives Java hosts the same one-call installer, mock + * rules included: * ```java * OkHttpClient client = DevConsoleOkHttp.install(new OkHttpClient.Builder(), DevConsole.networkRecorder()) - * .addInterceptor(new DevConsoleMockInterceptor(DevConsole.mockEngine())) * .build(); * ``` */ @@ -66,5 +82,6 @@ object DevConsoleOkHttp { builder: OkHttpClient.Builder, recorder: NetworkTransactionRecorder, existingEventListenerFactory: EventListener.Factory? = null, - ): OkHttpClient.Builder = builder.installDevConsole(recorder, existingEventListenerFactory) + mockEngine: MockEngine? = MockEngineRegistry.active(), + ): OkHttpClient.Builder = builder.installDevConsole(recorder, existingEventListenerFactory, mockEngine) } diff --git a/sdk/network-okhttp/src/test/kotlin/io/devconsole/network/okhttp/DevConsoleOkHttpMockInstallTest.kt b/sdk/network-okhttp/src/test/kotlin/io/devconsole/network/okhttp/DevConsoleOkHttpMockInstallTest.kt new file mode 100644 index 0000000..4ec6dfa --- /dev/null +++ b/sdk/network-okhttp/src/test/kotlin/io/devconsole/network/okhttp/DevConsoleOkHttpMockInstallTest.kt @@ -0,0 +1,161 @@ +package io.devconsole.network.okhttp + +import io.devconsole.mocks.MockAction +import io.devconsole.mocks.MockEngine +import io.devconsole.mocks.MockEngineRegistry +import io.devconsole.mocks.MockRule +import io.devconsole.mocks.okhttp.DevConsoleMockInterceptor +import io.devconsole.network.InMemoryNetworkTransactionStore +import io.devconsole.network.NetworkCaptureFactory +import io.devconsole.network.NetworkCursorCodec +import io.devconsole.network.NetworkTransactionRecorder +import io.devconsole.security.RedactionEngine +import io.devconsole.security.RedactionPolicy +import okhttp3.OkHttpClient +import okhttp3.Request +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.MockWebServer +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * Mock rules used to need a second line at every call site -- + * `.addInterceptor(DevConsoleMockInterceptor(DevConsole.mockEngine()))` -- and the Mocks screen sat + * inert for anyone who never read that far. [installDevConsole] now wires it from the engine the + * running DevConsole published to [MockEngineRegistry]. + * + * Every assertion here is about a real call through a real [MockWebServer]: a served mock is one the + * upstream server never sees, which no amount of interceptor-list inspection would actually prove. + */ +class DevConsoleOkHttpMockInstallTest { + @After fun tearDown() = MockEngineRegistry.clear() + + @Test + fun `installDevConsole serves the published engine's rules without a second interceptor`() { + MockEngineRegistry.publish( + MockEngine( + listOf( + MockRule( + id = "orders", + priority = 1, + path = "/orders", + action = MockAction.StaticResponse(202, "mocked-body"), + ), + ), + ), + ) + withServerAndClient { server, client -> + server.enqueue(MockResponse().setBody("upstream")) + + client.newCall(Request.Builder().url(server.url("/orders")).build()).execute().use { + assertEquals(202, it.code) + assertEquals("mocked-body", it.body!!.string()) + } + + assertEquals("the mock must short-circuit before the network", 0, server.requestCount) + } + } + + /** + * The default has to stay invisible until a rule matches. A host with mocking wired but no rules + * -- which is every host on first run now -- must see its traffic untouched. + */ + @Test + fun `an engine with no matching rule passes the call through untouched`() { + MockEngineRegistry.publish(MockEngine(listOf(MockRule("other", 1, path = "/somewhere-else")))) + withServerAndClient { server, client -> + server.enqueue(MockResponse().setBody("upstream")) + + client.newCall(Request.Builder().url(server.url("/orders")).build()).execute().use { + assertEquals("upstream", it.body!!.string()) + } + + assertEquals(1, server.requestCount) + } + } + + /** Before `DevConsole.initialize` there is no engine, and the installer must still build a client. */ + @Test + fun `no published engine means no mock interceptor`() { + MockEngineRegistry.clear() + withServerAndClient { server, client -> + server.enqueue(MockResponse().setBody("upstream")) + + client.newCall(Request.Builder().url(server.url("/orders")).build()).execute().use { + assertEquals("upstream", it.body!!.string()) + } + + assertEquals(1, server.requestCount) + } + } + + /** + * A host that keeps its old manual `.addInterceptor(DevConsoleMockInterceptor(...))` line now has + * two of them in the chain. Most actions short-circuit, so the second never runs -- but a + * `Delay` whose next action proceeds up the chain reaches both, and each would sleep the full + * duration, silently doubling every simulated latency the moment the host upgraded. The second + * pass must recognise the first and stand down. + */ + @Test + fun `a hosts own mock interceptor does not double apply a delay on top of the installed one`() { + val engine = + MockEngine( + listOf( + MockRule( + id = "slow", + priority = 1, + path = "/orders", + action = MockAction.Delay(DELAY_MS, MockAction.Passthrough), + ), + ), + ) + MockEngineRegistry.publish(engine) + val server = MockWebServer() + server.start() + try { + server.enqueue(MockResponse().setBody("upstream")) + val client = + OkHttpClient + .Builder() + .installDevConsole(recorder()) + .addInterceptor(DevConsoleMockInterceptor(engine)) + .build() + + val startedAt = System.nanoTime() + client.newCall(Request.Builder().url(server.url("/orders")).build()).execute().use { + assertEquals("upstream", it.body!!.string()) + } + val elapsedMs = (System.nanoTime() - startedAt) / NANOS_PER_MS + + assertTrue( + "the delay must be applied once, not twice (took ${elapsedMs}ms)", + elapsedMs < DELAY_MS * 2, + ) + } finally { + server.shutdown() + } + } + + private fun recorder() = + NetworkTransactionRecorder( + NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())), + InMemoryNetworkTransactionStore(NetworkCursorCodec("mock-install-test-key".encodeToByteArray())), + ) + + private fun withServerAndClient(block: (MockWebServer, OkHttpClient) -> Unit) { + val server = MockWebServer() + server.start() + try { + block(server, OkHttpClient.Builder().installDevConsole(recorder()).build()) + } finally { + server.shutdown() + } + } + + private companion object { + const val DELAY_MS = 300L + const val NANOS_PER_MS = 1_000_000L + } +}