diff --git a/docs/SECURITY_AND_REDACTION.md b/docs/SECURITY_AND_REDACTION.md index 7634a8e..b748e41 100644 --- a/docs/SECURITY_AND_REDACTION.md +++ b/docs/SECURITY_AND_REDACTION.md @@ -11,11 +11,10 @@ regardless of which inspector captured it. ## Default policy -`RedactionPolicy.default()`'s 25 sensitive field names (case-insensitive, matched against header +`RedactionPolicy.default()`'s sensitive field names (case-insensitive, matched against header names, JSON keys, and form field names): ```text -authorization proxy-authorization www-authenticate authentication cookie set-cookie x-api-key api-key apikey x-auth-token x-access-token x-csrf-token x-xsrf-token access_token refresh_token id_token @@ -24,9 +23,7 @@ passphrase secret client_secret private_key session_id ``` -A matched value is replaced wholesale with ``. Independently of the field-name list, any -`Bearer ` text pattern is redacted wherever it appears (e.g. inside a body that isn't valid -JSON/form data), so a leaked bearer token in a non-standard location is still caught. +A matched value is replaced wholesale with ``. `Authorization` headers and Bearer tokens are kept unredacted by default to allow developers to inspect and copy tokens during debugging; custom `textPatterns` and additional `sensitiveFieldNames` can be configured via `RedactionPolicy` if further redaction is desired. ## Redaction strategies beyond removal diff --git a/docs/THREAT_MODEL.md b/docs/THREAT_MODEL.md index 266f19b..791b6a0 100644 --- a/docs/THREAT_MODEL.md +++ b/docs/THREAT_MODEL.md @@ -165,8 +165,8 @@ a remedy, not a proof of control. ## Redaction is an allowlist, and allowlists miss things -`RedactionPolicy.default()` matches a fixed set of ~25 field names (case-insensitively) against -header names, JSON keys, and form/query field names, plus one regex for `Bearer ` text. See +`RedactionPolicy.default()` matches a set of sensitive field names (case-insensitively) against +header names, JSON keys, and form/query field names. See [SECURITY_AND_REDACTION.md](SECURITY_AND_REDACTION.md) for the exact list. Everything not on that list is transmitted and stored **verbatim**. In practice that means: 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 e6bf7cb..f2bbf48 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 @@ -963,7 +963,12 @@ private fun ConnectUrlPanel( TextButton( onClick = { clipboard.setText(AnnotatedString(connectUrl)) - val message = if (usesSessionCode) "Session code copied -- keep it private" else "Dashboard URL copied" + val message = + if (usesSessionCode) { + "Session code copied -- keep it private" + } else { + "Dashboard URL copied" + } Toast.makeText(context, message, Toast.LENGTH_SHORT).show() }, modifier = Modifier.align(Alignment.End), 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 81eb5ec..a59e70b 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 @@ -332,7 +332,12 @@ class MainActivity : Activity() { val url = connectUrl ?: return@setOnClickListener val clipboard = getSystemService(ClipboardManager::class.java) clipboard.setPrimaryClip(ClipData.newPlainText("DevConsole dashboard URL", url)) - val message = if (url.contains("#code=")) "Session code copied -- keep it private" else "Dashboard URL copied" + val message = + if (url.contains("#code=")) { + "Session code copied -- keep it private" + } else { + "Dashboard URL copied" + } Toast.makeText(this@MainActivity, message, Toast.LENGTH_SHORT).show() } } @@ -501,7 +506,7 @@ class MainActivity : Activity() { "No session code is required in the default open mode. Use SESSION_CODE before sharing " + "a LAN-bound dashboard on an untrusted network.\n\n" } + - "This debugging session uses local-network HTTP. Other participants on an untrusted network " + + "This debugging session uses local-network HTTP. Other participants on an untrusted network " + "may observe or modify traffic. Use ADB localhost mode or a trusted isolated network " + "for sensitive testing." statusView.text = message diff --git a/sdk/composer/src/test/kotlin/io/devconsole/composer/ComposerRequestTest.kt b/sdk/composer/src/test/kotlin/io/devconsole/composer/ComposerRequestTest.kt index aeb0641..29a1d7c 100644 --- a/sdk/composer/src/test/kotlin/io/devconsole/composer/ComposerRequestTest.kt +++ b/sdk/composer/src/test/kotlin/io/devconsole/composer/ComposerRequestTest.kt @@ -66,7 +66,7 @@ class ComposerRequestTest { ComposerRequest( method = "POST", url = "https://api.test/orders?access_token=url-canary", - headers = mapOf("Authorization" to "Bearer header-canary", "Accept" to "application/json"), + headers = mapOf("Cookie" to "session=header-canary", "Accept" to "application/json"), body = """{"password":"body-canary","keep":"visible"}""", query = listOf(ComposerQueryParameter("token", "query-canary")), formFields = mapOf("client_secret" to "form-canary"), diff --git a/sdk/core/src/test/kotlin/io/devconsole/core/EventBatchWriterTest.kt b/sdk/core/src/test/kotlin/io/devconsole/core/EventBatchWriterTest.kt index 4bca35d..18d78b5 100644 --- a/sdk/core/src/test/kotlin/io/devconsole/core/EventBatchWriterTest.kt +++ b/sdk/core/src/test/kotlin/io/devconsole/core/EventBatchWriterTest.kt @@ -19,8 +19,8 @@ class EventBatchWriterTest { val writer = EventBatchWriter(store, this, capacity = 2, maxBatchSize = 2, flushIntervalMs = 1000) writer.start() - writer.submit(event("Bearer first-secret")) - writer.submit(event("Bearer second-secret")) + writer.submit(event("password=first-secret")) + writer.submit(event("password=second-secret")) testScheduler.runCurrent() assertEquals(1, store.batches.size) diff --git a/sdk/core/src/test/kotlin/io/devconsole/core/EventPipelineTest.kt b/sdk/core/src/test/kotlin/io/devconsole/core/EventPipelineTest.kt index 928704f..1675545 100644 --- a/sdk/core/src/test/kotlin/io/devconsole/core/EventPipelineTest.kt +++ b/sdk/core/src/test/kotlin/io/devconsole/core/EventPipelineTest.kt @@ -44,14 +44,14 @@ class EventPipelineTest { pluginId = "network", type = "network.request", severity = EventSeverity.INFO, - summary = "Authorization: Bearer raw-token", - tags = mapOf("Authorization" to "Bearer another-token", "route" to "/orders"), + summary = "password=raw-token", + tags = mapOf("Cookie" to "session=another-token", "route" to "/orders"), ), ) val event = pipeline.snapshot().single() assertFalse(event.summary.contains("raw-token")) - assertEquals("", event.tags.getValue("Authorization")) + assertEquals("", event.tags.getValue("Cookie")) assertEquals("/orders", event.tags.getValue("route")) } diff --git a/sdk/export/src/test/kotlin/io/devconsole/export/EventExportWriterTest.kt b/sdk/export/src/test/kotlin/io/devconsole/export/EventExportWriterTest.kt index c303a20..99f100a 100644 --- a/sdk/export/src/test/kotlin/io/devconsole/export/EventExportWriterTest.kt +++ b/sdk/export/src/test/kotlin/io/devconsole/export/EventExportWriterTest.kt @@ -23,7 +23,7 @@ class EventExportWriterTest { ExportRequest( sessionId = "session-1", destination = destination, - events = listOf(event(summary = "request Bearer export-secret")), + events = listOf(event(summary = "password=export-secret")), ), ) @@ -122,7 +122,7 @@ class EventExportWriterTest { "event-1" to TimelineAnnotation( bookmarked = true, - note = "Authorization: Bearer note-secret", + note = "password=note-secret", ), ), ) @@ -131,7 +131,7 @@ class EventExportWriterTest { ZipFile(destination).use { zip -> val timeline = zip.getInputStream(zip.getEntry("timeline.jsonl")).bufferedReader().readText() assertTrue(timeline.contains("\"bookmarked\":true")) - assertTrue(timeline.contains("\"note\":\"Authorization: \"")) + assertTrue(timeline.contains("\"note\":\"password=\"")) assertFalse(timeline.contains("note-secret")) } } finally { @@ -316,7 +316,7 @@ class EventExportWriterTest { val request = evidenceRequest(destination).withEvidenceBundle( baseEvidenceBundle().copy( - reportMarkdown = "Summary: Authorization: Bearer report-secret", + reportMarkdown = "password=report-secret", ), ) diff --git a/sdk/full/src/main/kotlin/io/devconsole/FullInspectorDataSource.kt b/sdk/full/src/main/kotlin/io/devconsole/FullInspectorDataSource.kt index 8b49cf1..473f8c0 100644 --- a/sdk/full/src/main/kotlin/io/devconsole/FullInspectorDataSource.kt +++ b/sdk/full/src/main/kotlin/io/devconsole/FullInspectorDataSource.kt @@ -1336,6 +1336,11 @@ private fun NetworkTransaction.evidenceDetailJson(): String = capture.request.url.path .escapeJson(), ).append('"') + append(",\"query\":\"") + .append( + capture.request.url.queryString + .escapeJson(), + ).append('"') append(",\"status\":").append(capture.response?.statusCode ?: "null") val contentType = (capture.response?.contentType ?: capture.request.contentType).orEmpty() append(",\"contentType\":\"").append(contentType.escapeJson()).append('"') diff --git a/sdk/full/src/test/kotlin/io/devconsole/AndroidFileInspectorTest.kt b/sdk/full/src/test/kotlin/io/devconsole/AndroidFileInspectorTest.kt index 173de14..0348515 100644 --- a/sdk/full/src/test/kotlin/io/devconsole/AndroidFileInspectorTest.kt +++ b/sdk/full/src/test/kotlin/io/devconsole/AndroidFileInspectorTest.kt @@ -50,7 +50,7 @@ class AndroidFileInspectorTest { @Test fun `preview redacts text file contents`() { File(application.filesDir, "secret.txt") - .writeText("authorization: Bearer sk-super-secret-value-1234567890") + .writeText("password=sk-super-secret-value-1234567890") val preview = inspector.preview("files", "secret.txt") diff --git a/sdk/full/src/test/kotlin/io/devconsole/AndroidInspectorExporterTest.kt b/sdk/full/src/test/kotlin/io/devconsole/AndroidInspectorExporterTest.kt index 7a1e156..5e17cc5 100644 --- a/sdk/full/src/test/kotlin/io/devconsole/AndroidInspectorExporterTest.kt +++ b/sdk/full/src/test/kotlin/io/devconsole/AndroidInspectorExporterTest.kt @@ -59,7 +59,7 @@ class AndroidInspectorExporterTest { NetworkRequestInput( method = "GET", url = "https://api.example.test$path", - headers = mapOf("Authorization" to "Bearer $SECRET_TOKEN"), + headers = mapOf("Cookie" to "session=$SECRET_TOKEN"), ), NetworkResponseInput( statusCode = 200, @@ -187,7 +187,7 @@ class AndroidInspectorExporterTest { wallTimeMs = 10, monoTimeNs = 10, severity = 3, - summary = "Checkout failed: Authorization Bearer $SECRET_TOKEN", + summary = "password=$SECRET_TOKEN", tagsJson = "{}", payloadJson = null, ), diff --git a/sdk/full/src/test/kotlin/io/devconsole/AndroidPreferencesInspectorTest.kt b/sdk/full/src/test/kotlin/io/devconsole/AndroidPreferencesInspectorTest.kt index ebd7c42..6c53938 100644 --- a/sdk/full/src/test/kotlin/io/devconsole/AndroidPreferencesInspectorTest.kt +++ b/sdk/full/src/test/kotlin/io/devconsole/AndroidPreferencesInspectorTest.kt @@ -49,12 +49,12 @@ class AndroidPreferencesInspectorTest { application .getSharedPreferences("secret_prefs", Context.MODE_PRIVATE) .edit() - .putString("auth_token", "Bearer sk-super-secret-value-1234567890") + .putString("access_token", "sk-super-secret-value-1234567890") .putInt("count", 3) .commit() val file = inspector.files().first { it.name == "secret_prefs" } - val tokenEntry = file.entries.first { it.key == "auth_token" } + val tokenEntry = file.entries.first { it.key == "access_token" } assertFalse(tokenEntry.value.contains("sk-super-secret-value-1234567890")) assertTrue(tokenEntry.redacted) diff --git a/sdk/full/src/test/kotlin/io/devconsole/CrashCaptureTest.kt b/sdk/full/src/test/kotlin/io/devconsole/CrashCaptureTest.kt index f4b36ed..2408180 100644 --- a/sdk/full/src/test/kotlin/io/devconsole/CrashCaptureTest.kt +++ b/sdk/full/src/test/kotlin/io/devconsole/CrashCaptureTest.kt @@ -96,10 +96,10 @@ class CrashCaptureTest { @Test fun `the crash payload is redacted`() { - capture().recordAnr("main", "called with Authorization: Bearer topsecret123") + capture().recordAnr("main", "password=topsecret123") assertTrue( - "expected the token to be redacted: ${appended.single().payloadJson}", + "expected the password to be redacted: ${appended.single().payloadJson}", "topsecret123" !in appended.single().payloadJson.orEmpty(), ) } diff --git a/sdk/full/src/test/kotlin/io/devconsole/CrashPolicyGatingTest.kt b/sdk/full/src/test/kotlin/io/devconsole/CrashPolicyGatingTest.kt index 0c995c6..4a5531e 100644 --- a/sdk/full/src/test/kotlin/io/devconsole/CrashPolicyGatingTest.kt +++ b/sdk/full/src/test/kotlin/io/devconsole/CrashPolicyGatingTest.kt @@ -27,7 +27,8 @@ import org.robolectric.annotation.Config @RunWith(RobolectricTestRunner::class) @Config(sdk = [34]) class CrashPolicyGatingTest { - private fun anrWatchdogThreadRunning(): Boolean = Thread.getAllStackTraces().keys.any { it.name == ANR_THREAD_NAME } + private fun anrWatchdogThreadRunning(): Boolean = + Thread.getAllStackTraces().keys.any { it.name == ANR_THREAD_NAME && it.isAlive } /** * Thread start/interrupt-triggered exit are asynchronous relative to the call that triggers @@ -89,6 +90,7 @@ class CrashPolicyGatingTest { @Test fun `anrWatchdogEnabled = false never starts the watchdog thread`() = runTest { + awaitThreadState(expectedRunning = false, timeoutMs = 2_000L) val provider = PlatformFacadeProvider() val config = DevConsoleConfig.default().withCrashPolicy(CrashPolicy(anrWatchdogEnabled = false)) provider.initialize(ApplicationProvider.getApplicationContext(), config) diff --git a/sdk/full/src/test/kotlin/io/devconsole/FullInspectorDataSourceTest.kt b/sdk/full/src/test/kotlin/io/devconsole/FullInspectorDataSourceTest.kt index 2fc1a01..2b41c2c 100644 --- a/sdk/full/src/test/kotlin/io/devconsole/FullInspectorDataSourceTest.kt +++ b/sdk/full/src/test/kotlin/io/devconsole/FullInspectorDataSourceTest.kt @@ -90,12 +90,13 @@ class FullInspectorDataSourceTest { id: String, startedAtEpochMs: Long, completedAtEpochMs: Long?, + url: String = "https://api.example.test/orders", ) { val capture = captureFactory.capture( NetworkRequestInput( method = "GET", - url = "https://api.example.test/orders", + url = url, headers = mapOf("X-Request-Id" to id), ), NetworkResponseInput( @@ -728,6 +729,29 @@ class FullInspectorDataSourceTest { assertTrue(evidence.items("session-1").isEmpty()) } + /** + * The traffic list row shows path + query, and it reads that query back off `url` -- so the + * mapping has to carry the query across there, while `path` stays the bare endpoint that + * mock-rule prefill escapes into a regex. + */ + @Test + fun `snapshot carries a transaction's query string on the url, not folded into the path`() { + val store = networkStore() + recordTransaction( + store, + "tx-query", + startedAtEpochMs = 0, + completedAtEpochMs = 5, + url = "https://api.example.test/orders?status=open&page=2", + ) + val source = FullInspectorDataSource(store, MockEngine(emptyList()), configSupplier = { null }) + + val transaction = source.snapshot().transactions.single() + + assertEquals("/orders", transaction.path) + assertEquals("https://api.example.test/orders?status=open&page=2", transaction.url) + } + @Test fun `snapshot maps transactions, mock rules, and capabilities from the underlying engines`() { val store = networkStore() diff --git a/sdk/full/src/test/kotlin/io/devconsole/RemoteConfigInspectorTest.kt b/sdk/full/src/test/kotlin/io/devconsole/RemoteConfigInspectorTest.kt index b8d8d6f..21c9179 100644 --- a/sdk/full/src/test/kotlin/io/devconsole/RemoteConfigInspectorTest.kt +++ b/sdk/full/src/test/kotlin/io/devconsole/RemoteConfigInspectorTest.kt @@ -207,11 +207,18 @@ class RemoteConfigInspectorTest { } @Test - fun `a bearer token inside an ordinary value is still scrubbed`() { - val entries = redactingBoundary().apply(listOf(entry("welcome_banner", "Bearer abc123def"))) + fun `a secret inside an ordinary value is still scrubbed when policy specifies pattern`() { + val policy = + RedactionPolicy( + sensitiveFieldNames = emptySet(), + textPatterns = listOf(Regex("secret-[0-9]+")), + ) + val entries = + RedactingRemoteConfig(RedactionEngine(policy), policy) + .apply(listOf(entry("welcome_banner", "secret-12345"))) assertTrue(entries.single().redacted) - assertFalse(entries.single().value.contains("abc123def")) + assertFalse(entries.single().value.contains("secret-12345")) } @Test diff --git a/sdk/logs/src/test/kotlin/io/devconsole/logs/LogRecorderTest.kt b/sdk/logs/src/test/kotlin/io/devconsole/logs/LogRecorderTest.kt index 0788ccc..1c9bc8d 100644 --- a/sdk/logs/src/test/kotlin/io/devconsole/logs/LogRecorderTest.kt +++ b/sdk/logs/src/test/kotlin/io/devconsole/logs/LogRecorderTest.kt @@ -15,13 +15,13 @@ class LogRecorderTest { @Test fun `records a redacted entry`() { LogRecorder(redaction, sink, nowEpochMs = { 42L }) - .record(LogLevel.INFO, "Checkout", "calling with Authorization: Bearer abc123def") + .record(LogLevel.INFO, "Checkout", "password=abc123def") val entry = emitted.single() assertEquals(LogLevel.INFO, entry.level) assertEquals("Checkout", entry.tag) assertEquals(42L, entry.timestampEpochMs) - assertTrue("expected the bearer token to be redacted, got: ${entry.message}", "abc123def" !in entry.message) + assertTrue("expected the password to be redacted, got: ${entry.message}", "abc123def" !in entry.message) assertNull(entry.stackTrace) } diff --git a/sdk/network/api/network.api b/sdk/network/api/network.api index 05bcfb1..0f08c88 100644 --- a/sdk/network/api/network.api +++ b/sdk/network/api/network.api @@ -571,6 +571,7 @@ public final class io/devconsole/network/NetworkUrl { public final fun getHost ()Ljava/lang/String; public final fun getPath ()Ljava/lang/String; public final fun getQuery ()Ljava/util/Map; + public final fun getQueryString ()Ljava/lang/String; public final fun getScheme ()Ljava/lang/String; public fun hashCode ()I public fun toString ()Ljava/lang/String; diff --git a/sdk/network/src/main/kotlin/io/devconsole/network/NetworkCapture.kt b/sdk/network/src/main/kotlin/io/devconsole/network/NetworkCapture.kt index 8134692..c72974a 100644 --- a/sdk/network/src/main/kotlin/io/devconsole/network/NetworkCapture.kt +++ b/sdk/network/src/main/kotlin/io/devconsole/network/NetworkCapture.kt @@ -80,10 +80,17 @@ data class NetworkUrl( val path: String, val query: Map, ) { + /** + * The already-redacted query in `a=1&b=2` form, empty when the request carried no parameters. + * Split out of [display] so a list row can show the query beside the path without having to + * re-parse a full URL string. + */ + val queryString: String get() = query.entries.joinToString("&") { "${it.key}=${it.value}" } + val display: String get() = buildString { append("$scheme://$host$path") - if (query.isNotEmpty()) append('?').append(query.entries.joinToString("&") { "${it.key}=${it.value}" }) + if (query.isNotEmpty()) append('?').append(queryString) } } diff --git a/sdk/network/src/test/kotlin/io/devconsole/network/NetworkCaptureFactoryTest.kt b/sdk/network/src/test/kotlin/io/devconsole/network/NetworkCaptureFactoryTest.kt index c10cc4c..1412e52 100644 --- a/sdk/network/src/test/kotlin/io/devconsole/network/NetworkCaptureFactoryTest.kt +++ b/sdk/network/src/test/kotlin/io/devconsole/network/NetworkCaptureFactoryTest.kt @@ -11,21 +11,22 @@ class NetworkCaptureFactoryTest { private val factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())) @Test - fun `redacts headers query and textual body before producing capture`() { + fun `redacts headers query and textual body before producing capture while preserving authorization`() { val capture = factory.capture( request = NetworkRequestInput( method = "POST", url = "https://example.test/orders?access_token=raw-secret", - headers = mapOf("Authorization" to "Bearer header-secret"), - body = "Bearer body-secret".encodeToByteArray(), + headers = mapOf("Authorization" to "Bearer header-token", "Cookie" to "session=header-secret"), + body = "{\"password\":\"body-secret\"}".encodeToByteArray(), contentType = "application/json", ), response = null, ) - assertEquals("", capture.request.headers.getValue("Authorization")) + assertEquals("Bearer header-token", capture.request.headers.getValue("Authorization")) + assertEquals("", capture.request.headers.getValue("Cookie")) assertFalse( capture.request.url.display .contains("raw-secret"), diff --git a/sdk/network/src/test/kotlin/io/devconsole/network/NetworkExportTest.kt b/sdk/network/src/test/kotlin/io/devconsole/network/NetworkExportTest.kt index dcf697f..fef37a5 100644 --- a/sdk/network/src/test/kotlin/io/devconsole/network/NetworkExportTest.kt +++ b/sdk/network/src/test/kotlin/io/devconsole/network/NetworkExportTest.kt @@ -15,8 +15,8 @@ class NetworkExportTest { NetworkRequestInput( method = "POST", url = "https://example.test/orders?access_token=query-secret", - headers = mapOf("Authorization" to "Bearer header-secret"), - body = "Bearer body-secret".encodeToByteArray(), + headers = mapOf("Cookie" to "session=header-secret"), + body = "{\"password\":\"body-secret\"}".encodeToByteArray(), contentType = "application/json", ), NetworkResponseInput(statusCode = 201), @@ -286,7 +286,7 @@ class NetworkExportTest { NetworkRequestInput( method = "POST", url = "https://example.test/orders", - headers = mapOf("Authorization" to "Bearer header-secret"), + headers = mapOf("Cookie" to "session=header-secret"), body = "{\"token\":\"body-secret\"}".encodeToByteArray(), contentType = "application/json", ), diff --git a/sdk/push/src/test/kotlin/io/devconsole/push/PushEventStoreTest.kt b/sdk/push/src/test/kotlin/io/devconsole/push/PushEventStoreTest.kt index 35094a1..430a258 100644 --- a/sdk/push/src/test/kotlin/io/devconsole/push/PushEventStoreTest.kt +++ b/sdk/push/src/test/kotlin/io/devconsole/push/PushEventStoreTest.kt @@ -22,7 +22,7 @@ class PushEventStoreTest { sentAtEpochMs = 10, receivedAtEpochMs = 20, notification = PushNotification(title = "New order", body = "Order #42"), - rawMetadata = mapOf("authorization" to "Bearer raw-secret"), + rawMetadata = mapOf("password" to "raw-secret"), lifecycle = PushLifecycle.OPENED, simulated = true, ), @@ -31,7 +31,7 @@ class PushEventStoreTest { assertEquals(PushLifecycle.OPENED, event.lifecycle) assertTrue(event.simulated) assertEquals("", event.data.getValue("access_token")) - assertEquals("", event.rawMetadata.getValue("authorization")) + assertEquals("", event.rawMetadata.getValue("password")) assertEquals(listOf(event), store.events()) } } diff --git a/sdk/security/src/main/kotlin/io/devconsole/security/RedactionEngine.kt b/sdk/security/src/main/kotlin/io/devconsole/security/RedactionEngine.kt index 4025a93..c5776cb 100644 --- a/sdk/security/src/main/kotlin/io/devconsole/security/RedactionEngine.kt +++ b/sdk/security/src/main/kotlin/io/devconsole/security/RedactionEngine.kt @@ -33,10 +33,6 @@ data class RedactionPolicy( RedactionPolicy( sensitiveFieldNames = setOf( - "authorization", - "proxy-authorization", - "www-authenticate", - "authentication", "cookie", "set-cookie", "x-api-key", @@ -59,7 +55,7 @@ data class RedactionPolicy( "private_key", "session_id", ), - textPatterns = listOf(Regex("Bearer\\s+[A-Za-z0-9._~-]+", RegexOption.IGNORE_CASE)), + textPatterns = emptyList(), ) } } diff --git a/sdk/security/src/test/kotlin/io/devconsole/security/RedactionEngineTest.kt b/sdk/security/src/test/kotlin/io/devconsole/security/RedactionEngineTest.kt index 2b9532b..2a444ce 100644 --- a/sdk/security/src/test/kotlin/io/devconsole/security/RedactionEngineTest.kt +++ b/sdk/security/src/test/kotlin/io/devconsole/security/RedactionEngineTest.kt @@ -10,11 +10,17 @@ class RedactionEngineTest { @Test fun `redacts default sensitive headers case insensitively`() { - val redacted = engine.redactFields(mapOf("Authorization" to "Bearer secret", "Accept" to "application/json")) - assertEquals("", redacted["Authorization"]) + val redacted = engine.redactFields(mapOf("Cookie" to "session=secret", "Accept" to "application/json")) + assertEquals("", redacted["Cookie"]) assertEquals("application/json", redacted["Accept"]) } + @Test + fun `preserves authorization header unredacted by default`() { + val fields = engine.redactFields(mapOf("Authorization" to "Bearer secret-token-123")) + assertEquals("Bearer secret-token-123", fields["Authorization"]) + } + @Test fun `redacts access token query values before storage`() { assertEquals("", engine.redactFields(mapOf("access_token" to "abc"))["access_token"]) @@ -22,13 +28,27 @@ class RedactionEngineTest { @Test fun `bounds text before applying regex rules`() { - val result = engine.redactText("Bearer abc.def", maxLength = 8) + val regexEngine = + RedactionEngine( + RedactionPolicy( + sensitiveFieldNames = emptySet(), + textPatterns = listOf(Regex("Bearer\\s+[A-Za-z0-9._~-]+", RegexOption.IGNORE_CASE)), + ), + ) + val result = regexEngine.redactText("Bearer abc.def", maxLength = 8) assertFalse(result.contains("abc.def")) } @Test fun `applies redaction before enforcing preview limit`() { - val result = engine.redactText("Bearer very-secret-token", maxLength = 10) + val regexEngine = + RedactionEngine( + RedactionPolicy( + sensitiveFieldNames = emptySet(), + textPatterns = listOf(Regex("Bearer\\s+[A-Za-z0-9._~-]+", RegexOption.IGNORE_CASE)), + ), + ) + val result = regexEngine.redactText("Bearer very-secret-token", maxLength = 10) assertFalse(result.contains("very-secret-token")) assertEquals("", result) @@ -49,7 +69,7 @@ class RedactionEngineTest { mapOf( "X-Auth-Token" to "abc123", "x-access-token" to "def456", - "Authentication" to "ghi789", + "x-api-key" to "ghi789", "jwt" to "eyJhbGciOi", "token" to "opaque", ), diff --git a/sdk/server-api/src/main/kotlin/io/devconsole/server/api/LocalServerEngine.kt b/sdk/server-api/src/main/kotlin/io/devconsole/server/api/LocalServerEngine.kt index 701eee3..4fef1ab 100644 --- a/sdk/server-api/src/main/kotlin/io/devconsole/server/api/LocalServerEngine.kt +++ b/sdk/server-api/src/main/kotlin/io/devconsole/server/api/LocalServerEngine.kt @@ -202,6 +202,7 @@ sealed interface SessionCodeExchangeResult { * host's `EditingCapabilities` flags instead of a session-level role. [SessionCodeAuthority] is the * sole way a session gets minted, via [createSession]. */ +@Suppress("TooManyFunctions") class SessionAuthority( private val nowEpochMs: () -> Long = System::currentTimeMillis, private val sessionTtlMs: Long = DEFAULT_SESSION_TTL_MS, diff --git a/sdk/server-ktor/src/main/kotlin/io/devconsole/server/ktor/DevConsoleKtorModule.kt b/sdk/server-ktor/src/main/kotlin/io/devconsole/server/ktor/DevConsoleKtorModule.kt index 435279a..dce61ec 100644 --- a/sdk/server-ktor/src/main/kotlin/io/devconsole/server/ktor/DevConsoleKtorModule.kt +++ b/sdk/server-ktor/src/main/kotlin/io/devconsole/server/ktor/DevConsoleKtorModule.kt @@ -5347,7 +5347,9 @@ private fun NetworkTransaction.summaryJson(): String { "\"completedAtEpochMs\":${completedAtEpochMs ?: "null"},\"durationMs\":${durationMs ?: "null"}," + "\"method\":\"${capture.request.method.escapeJson()}\"," + "\"host\":\"${capture.request.url.host.escapeJson()}\"," + - "\"path\":\"${capture.request.url.path.escapeJson()}\",\"status\":${capture.response?.statusCode ?: "null"}," + + "\"path\":\"${capture.request.url.path.escapeJson()}\"," + + "\"query\":\"${capture.request.url.queryString.escapeJson()}\"," + + "\"status\":${capture.response?.statusCode ?: "null"}," + "\"contentType\":\"$contentType\"," + "\"error\":$error,\"tags\":$tags,\"correlationId\":$correlationId}" } diff --git a/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.css b/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.css index 69922f0..4a23a99 100644 --- a/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.css +++ b/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.css @@ -781,6 +781,8 @@ body.detail-zoom .split-shell.collapse-detail { grid-template-columns: 1fr; } font-family: var(--font-mono); font-size: var(--d-row-main-font); color: var(--ink); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +/* Query string trailing a Network row's path: present and readable, but never louder than the endpoint. */ +.row-main-sub { color: var(--text-3); } .row-tag { flex: 0 0 auto; font-family: var(--font-mono); font-size: 9.5px; font-weight: 700; letter-spacing: 0.06em; padding: 1px 4px; border-radius: 99px; border: 1px solid var(--border-strong); diff --git a/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.js b/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.js index 2fbe8a3..295eb6f 100644 --- a/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.js +++ b/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.js @@ -338,7 +338,7 @@ * `checkbox: true` opts a row into the export-selection checkbox (Network only); `checked` * reflects whether `id` is currently in that selection. */ function rowHtml(opts) { - const { id, selected, badgeText, badgeTone, mainText, mainRtl, tagText, tagTone, duration, statusText, sTone, flagKind, flagLabel, checkbox, checked, posinset, setsize } = opts; + const { id, selected, badgeText, badgeTone, mainText, mainSub, mainRtl, tagText, tagTone, duration, statusText, sTone, flagKind, flagLabel, checkbox, checked, posinset, setsize } = opts; const flagId = opts.flagId ?? id; // selection id and evidence id may differ (socket frames) const flagged = flagKind ? isFlagged(flagKind, flagId) : false; // aria-posinset/aria-setsize: with the list virtualized, only a window of `role="option"` @@ -354,7 +354,7 @@ } ${esc(badgeText)} - ${esc(mainText)} + ${esc(mainText)}${mainSub ? `${esc(mainSub)}` : ''} ${tagText ? `${esc(tagText)}` : ''} ${esc(duration ?? '')} @@ -3461,6 +3461,9 @@ checkbox: true, checked: networkSelectedIds.has(t.id), badgeText: t.method, badgeTone: methodTone(t.method), mainText: t.path, + // The query is what separates two rows on the same endpoint, so it belongs in the row -- + // dimmed and after the path, which stays the part that survives the ellipsis. + mainSub: t.query ? '?' + t.query : '', // Single row-tag slot: a pinned diff baseline always wins over the mocked marker. tagText: networkPinnedId === t.id ? 'BASE' : t.tags?.mocked === 'true' ? 'MOCK' : false, tagTone: 'put', @@ -4456,7 +4459,7 @@ } function copyStateJson() { if (selectedStateValue === undefined || selectedStateValue === null) return; - navigator.clipboard?.writeText(JSON.stringify(selectedStateValue, null, 2)).then(() => toast('State copied.')); + copyToClipboard(JSON.stringify(selectedStateValue, null, 2), 'State'); } /** The command body is raw text, not JSON — inputSchema only tells us how to *shape* the * control (a boolean picker, an enum select, a number field, or a free-text/JSON textarea for @@ -5055,7 +5058,7 @@ const lines = [dbLastRows.columns.map(esc2).join(',')].concat( dbLastRows.rows.map((row) => dbLastRows.columns.map((c, i) => esc2(Array.isArray(row) ? row[i] : row[c])).join(',')), ); - navigator.clipboard?.writeText(lines.join('\n')).then(() => toast((dbSelectedTable || 'Table') + ' copied as CSV')); + copyToClipboard(lines.join('\n'), (dbSelectedTable || 'Table') + ' as CSV'); } // ================================================================ @@ -7186,10 +7189,36 @@ await show('mocks'); } async function copyToClipboard(text, label) { - try { - await navigator.clipboard.writeText(text); - toast(label + ' copied to clipboard.'); - } catch { + let copied = false; + if (navigator.clipboard && window.isSecureContext) { + try { + await navigator.clipboard.writeText(text); + copied = true; + } catch { + copied = false; + } + } + if (!copied) { + try { + const textarea = document.createElement('textarea'); + textarea.value = text; + textarea.style.position = 'fixed'; + textarea.style.left = '-9999px'; + textarea.style.top = '-9999px'; + textarea.style.opacity = '0'; + textarea.setAttribute('readonly', ''); + document.body.appendChild(textarea); + textarea.focus(); + textarea.select(); + copied = document.execCommand('copy'); + document.body.removeChild(textarea); + } catch { + copied = false; + } + } + if (copied) { + toast(label ? label + ' copied to clipboard.' : 'Copied to clipboard.'); + } else { toast('Clipboard access was denied.', 'error'); } } diff --git a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/DashboardAssetsTest.kt b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/DashboardAssetsTest.kt index 79d9c6f..e872f3c 100644 --- a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/DashboardAssetsTest.kt +++ b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/DashboardAssetsTest.kt @@ -16,6 +16,21 @@ class DashboardAssetsTest { assertTrue(dashboard.contains("")) } + /** + * A Network row used to print `t.path` alone, so `/orders?status=open` and `/orders?status=all` + * were two identical-looking rows -- the query is often the only thing that differs between + * captures of the same endpoint. It rides along as a dimmed suffix rather than replacing the + * main text, so the endpoint is still what survives the row's ellipsis. + */ + @Test + fun `network rows print the query string after the path`() { + val script = DashboardAssets.js() + + assertTrue(script.contains("mainSub: t.query ? '?' + t.query : ''")) + assertTrue(script.contains("class=\"row-main-sub\"")) + assertTrue(DashboardAssets.css().contains(".row-main-sub")) + } + @Test fun `socket message formatting does not require the structured clone browser API`() { val script = DashboardAssets.js() @@ -271,4 +286,21 @@ class DashboardAssetsTest { assertTrue(fn.contains("indexOf(needle")) assertFalse("query must never reach RegExp", fn.contains("RegExp")) } + + /** + * Regression for issue #40 ("Do not have access to copy from console"). In non-secure contexts + * (e.g. accessing DevConsole over plain HTTP via LAN), `navigator.clipboard` is unavailable. + * `copyToClipboard` must provide a fallback via `document.execCommand('copy')`. + */ + @Test + fun `copyToClipboard provides document execCommand copy fallback for insecure contexts`() { + val script = DashboardAssets.js() + val fn = + script + .substringAfter("async function copyToClipboard(") + .substringBefore("async function copyNetworkCurl()") + + assertTrue(fn.contains("execCommand('copy')")) + assertTrue(fn.contains("isSecureContext")) + } } diff --git a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/DevConsoleKtorModuleTest.kt b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/DevConsoleKtorModuleTest.kt index 8ac21b9..255147e 100644 --- a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/DevConsoleKtorModuleTest.kt +++ b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/DevConsoleKtorModuleTest.kt @@ -771,7 +771,7 @@ class DevConsoleKtorModuleTest { "https://api.test/orders?access_token=raw-secret", headers = mapOf( - "Authorization" to "Bearer header-secret", + "Cookie" to "session=header-secret", ), contentType = "application/json", ).withMetadata(NetworkRequestMetadata(tags = mapOf("source" to "composer"))), @@ -957,7 +957,7 @@ class DevConsoleKtorModuleTest { NetworkRequestInput( "GET", "https://api.test/orders", - headers = mapOf("Authorization" to "Bearer header-secret"), + headers = mapOf("Cookie" to "session=header-secret"), ), NetworkResponseInput(200), ), @@ -1076,6 +1076,48 @@ class DevConsoleKtorModuleTest { return count } + /** + * The list row is the only place an operator sees before opening a capture, and two calls to the + * same endpoint are told apart by their query alone -- so the summary carries it. It stays a + * field of its own rather than being folded into `path`, which the path facet, the `path=` + * filter and mock-rule prefill all still match on as the bare endpoint. + */ + @Test + fun `network transaction summary carries the redacted query string beside the path`() = + testApplication { + val sessions = SessionAuthority() + val sessionCodes = SessionCodeAuthority(sessions) + val network = InMemoryNetworkTransactionStore(NetworkCursorCodec("network-cursor-key".encodeToByteArray())) + network.record( + NetworkTransaction( + id = "transaction-query", + startedAtEpochMs = 100, + completedAtEpochMs = 120, + capture = + NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())).capture( + NetworkRequestInput("GET", "https://api.test/orders?status=open&page=2"), + NetworkResponseInput(200), + ), + ), + ) + application { + devConsoleModule(sessions, sessionCodes) { + networkTransactions = network + } + } + val session = client.exchangeSession(sessions, sessionCodes) + + val response = + client.get("/api/v1/network/transactions") { + header(HttpHeaders.Host, "localhost") + header(HttpHeaders.Authorization, "Bearer ${session.token}") + } + + assertEquals(HttpStatusCode.OK, response.status) + assertTrue(response.bodyAsText().contains("\"path\":\"/orders\"")) + assertTrue(response.bodyAsText().contains("\"query\":\"status=open&page=2\"")) + } + @Test fun `network transaction links correlated and time-window timeline events`() = testApplication { @@ -2889,7 +2931,7 @@ class DevConsoleKtorModuleTest { 2, 2, 1, - "Bearer export-secret", + "password=export-secret", attachmentId = "attachment-2", ), ), diff --git a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/FeatureFlagAndExportBundleRoutesTest.kt b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/FeatureFlagAndExportBundleRoutesTest.kt index 0d21915..760acb7 100644 --- a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/FeatureFlagAndExportBundleRoutesTest.kt +++ b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/FeatureFlagAndExportBundleRoutesTest.kt @@ -188,7 +188,7 @@ class FeatureFlagAndExportBundleRoutesTest { NetworkRequestInput( "GET", "https://api.test/orders", - headers = mapOf("Authorization" to "Bearer super-secret-token"), + headers = mapOf("Cookie" to "session=super-secret-token"), ), NetworkResponseInput(200), ), @@ -196,7 +196,7 @@ class FeatureFlagAndExportBundleRoutesTest { ) application { // redactionPolicy defaults to RedactionPolicy.default(), which masks the - // Authorization header the permissive capture-time policy above let through. + // Cookie header the permissive capture-time policy above let through. devConsoleModule(sessions, sessionCodes) { this.networkTransactions = networkStore } diff --git a/sdk/socket-okhttp/src/test/kotlin/io/devconsole/socket/okhttp/DevConsoleOkHttpWebSocketListenerTest.kt b/sdk/socket-okhttp/src/test/kotlin/io/devconsole/socket/okhttp/DevConsoleOkHttpWebSocketListenerTest.kt index 0ae34f0..a60f590 100644 --- a/sdk/socket-okhttp/src/test/kotlin/io/devconsole/socket/okhttp/DevConsoleOkHttpWebSocketListenerTest.kt +++ b/sdk/socket-okhttp/src/test/kotlin/io/devconsole/socket/okhttp/DevConsoleOkHttpWebSocketListenerTest.kt @@ -32,7 +32,7 @@ class DevConsoleOkHttpWebSocketListenerTest { val socket = FakeWebSocket() listener.recordOpen(socket) - listener.onMessage(socket, "Bearer socket-secret") + listener.onMessage(socket, "{\"password\":\"socket-secret\"}") val preview = ( diff --git a/sdk/socket-paho/src/test/kotlin/io/devconsole/socket/paho/DevConsolePahoMqttTest.kt b/sdk/socket-paho/src/test/kotlin/io/devconsole/socket/paho/DevConsolePahoMqttTest.kt index c4e6276..646aacd 100644 --- a/sdk/socket-paho/src/test/kotlin/io/devconsole/socket/paho/DevConsolePahoMqttTest.kt +++ b/sdk/socket-paho/src/test/kotlin/io/devconsole/socket/paho/DevConsolePahoMqttTest.kt @@ -54,7 +54,7 @@ class DevConsolePahoMqttTest { callback.messageArrived( "devconsole/demo/hello", - MqttMessage("Bearer socket-secret".toByteArray()).apply { qos = 1 }, + MqttMessage("{\"token\":\"socket-secret\"}".toByteArray()).apply { qos = 1 }, ) val connection = requireNotNull(store.connection(publisher.connectionId)) diff --git a/sdk/socket/src/test/kotlin/io/devconsole/socket/SocketRecorderTest.kt b/sdk/socket/src/test/kotlin/io/devconsole/socket/SocketRecorderTest.kt index 042c361..720b71e 100644 --- a/sdk/socket/src/test/kotlin/io/devconsole/socket/SocketRecorderTest.kt +++ b/sdk/socket/src/test/kotlin/io/devconsole/socket/SocketRecorderTest.kt @@ -15,7 +15,12 @@ class SocketRecorderTest { val recorder = SocketRecorder(RedactionEngine(RedactionPolicy.default()), store, clock = { 100L }) recorder.onOpen("connection", "wss://api.test/socket") - recorder.onMessage("connection", SocketDirection.RECEIVED, "Bearer socket-secret", "application/json") + recorder.onMessage( + "connection", + SocketDirection.RECEIVED, + "{\"password\":\"socket-secret\"}", + "application/json", + ) val preview = ( @@ -35,7 +40,12 @@ class SocketRecorderTest { SocketRecorder(RedactionEngine(RedactionPolicy.default()), store, enabled = false, clock = { 100L }) recorder.onOpen("connection", "wss://api.test/socket") - recorder.onMessage("connection", SocketDirection.RECEIVED, "Bearer socket-secret", "application/json") + recorder.onMessage( + "connection", + SocketDirection.RECEIVED, + "{\"password\":\"socket-secret\"}", + "application/json", + ) assertNull(store.connection("connection")) } @@ -155,7 +165,7 @@ class SocketRecorderTest { val recorder = SocketRecorder(RedactionEngine(RedactionPolicy.default()), store, clock = { 100L }) recorder.onOpen("connection", "tcp://broker.test:1883") - val contentType = MqttFrameMetadata.format("devices/Bearer socket-secret/status", qos = 1, retained = true) + val contentType = MqttFrameMetadata.format("devices/?password=socket-secret/status", qos = 1, retained = true) recorder.onMessage("connection", SocketDirection.RECEIVED, "payload", contentType) val storedContentType = diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDataSource.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDataSource.kt index 3f50afa..e49a66f 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDataSource.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDataSource.kt @@ -56,6 +56,25 @@ data class InspectorTransactionUi( val mockRuleId: String? = null, ) +/** + * The already-redacted query string, without its leading `?`; empty when the request carried none. + * + * Read back off [InspectorTransactionUi.url] rather than carried as a field of its own: the query is + * already in there, and widening the data class would change its constructor and `copy` signatures -- + * a binary break for every compiled caller. Adapters that predate `url` leave it blank and so report + * no query, exactly as they do today. + */ +internal fun InspectorTransactionUi.queryString(): String = url.substringAfter('?', "") + +/** + * The endpoint as a list row should show it -- `/v1/orders?status=open`. The query is often the only + * thing telling two captures of one endpoint apart, so a row printing [InspectorTransactionUi.path] + * alone shows the operator two identical lines. [InspectorTransactionUi.path] itself stays bare: it + * is what mock-rule prefill escapes into a regex and what the path facets group on. + */ +internal fun InspectorTransactionUi.pathWithQuery(): String = + queryString().let { if (it.isEmpty()) path else path + "?" + it } + /** * Shape of a captured body preview, mirroring `io.devconsole.network.BodyPreview` without a * `sdk:network` dependency. diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorNetworkSnippets.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorNetworkSnippets.kt index 51db8f2..8e391ff 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorNetworkSnippets.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorNetworkSnippets.kt @@ -102,7 +102,7 @@ internal fun InspectorTransactionUi.toJsonSnippet(): String = } /** [InspectorTransactionUi.url] is empty for adapters that predate that field. */ -private fun InspectorTransactionUi.displayUrl(): String = url.ifBlank { "https://$host$path" } +private fun InspectorTransactionUi.displayUrl(): String = url.ifBlank { "https://$host${pathWithQuery()}" } private fun Map.jsonObject(): String = if (isEmpty()) { diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveNetDetail.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveNetDetail.kt index c08a686..bffdc7a 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveNetDetail.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveNetDetail.kt @@ -174,7 +174,7 @@ private fun netGeneralEntries( mockDiff: JsonMockDiffResult?, ): List = buildList { - val url = transaction.url.ifBlank { "https://${transaction.host}${transaction.path}" } + val url = transaction.url.ifBlank { "https://${transaction.host}${transaction.pathWithQuery()}" } add(InspectorKeyValue("url", url)) add(InspectorKeyValue("method", transaction.method)) add(InspectorKeyValue("status", transaction.statusCode?.toString() ?: "no response received", statusColor)) diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveTrafficTab.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveTrafficTab.kt index 0d0f897..7ac909c 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveTrafficTab.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveTrafficTab.kt @@ -58,13 +58,14 @@ private data class TrafficStats( val rowsNewestFirst: List, ) -private fun List.matchesTrafficSearch(query: String): List { - if (query.isEmpty()) return this +private fun List.matchesTrafficSearch(search: String): List { + if (search.isEmpty()) return this return filter { tx -> - tx.path.lowercase(Locale.US).contains(query) || - tx.host.lowercase(Locale.US).contains(query) || - tx.requestPreview?.lowercase(Locale.US)?.contains(query) == true || - tx.responsePreview?.lowercase(Locale.US)?.contains(query) == true + tx.path.lowercase(Locale.US).contains(search) || + tx.queryString().lowercase(Locale.US).contains(search) || + tx.host.lowercase(Locale.US).contains(search) || + tx.requestPreview?.lowercase(Locale.US)?.contains(search) == true || + tx.responsePreview?.lowercase(Locale.US)?.contains(search) == true } } @@ -378,7 +379,7 @@ private fun TrafficRow( leadText = methodLeadText(transaction.method), leadColor = leadColor, leadContainerColor = leadBg, - title = transaction.path.substringBefore('?'), + title = transaction.pathWithQuery(), titleMaxLines = 2, subtitle = "${transaction.host} · ${formatCaptureClockTime(transaction.startedAtEpochMs)}$mockedSuffix", trailValue = transaction.statusCode?.toString() ?: "ERR", diff --git a/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorDataSourceTest.kt b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorDataSourceTest.kt index e22f750..bdf9291 100644 --- a/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorDataSourceTest.kt +++ b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorDataSourceTest.kt @@ -12,6 +12,46 @@ class InspectorDataSourceTest { DevConsoleInspectorBridge.reset() } + /** + * A traffic row that printed `path` alone rendered `/orders?status=open` and `/orders?status=all` + * as two identical lines. The query rides along from `url`, and `path` stays bare. + */ + @Test + fun `pathWithQuery appends the query a transaction's url carries`() { + val transaction = + InspectorTransactionUi( + id = "tx-1", + method = "GET", + host = "api.example.test", + path = "/orders", + statusCode = 200, + durationMs = 42, + url = "https://api.example.test/orders?status=open&page=2", + ) + + assertEquals("status=open&page=2", transaction.queryString()) + assertEquals("/orders?status=open&page=2", transaction.pathWithQuery()) + } + + @Test + fun `pathWithQuery is the bare path for a query-less capture and for a url-less adapter`() { + val noQuery = + InspectorTransactionUi( + id = "tx-1", + method = "GET", + host = "api.example.test", + path = "/orders", + statusCode = 200, + durationMs = 42, + url = "https://api.example.test/orders", + ) + val noUrl = noQuery.copy(url = "") + + assertEquals("", noQuery.queryString()) + assertEquals("/orders", noQuery.pathWithQuery()) + assertEquals("/orders", noUrl.pathWithQuery()) + } + @Test fun `bridge is safely unavailable before full runtime installation`() { val snapshot = DevConsoleInspectorBridge.source().snapshot()