Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,51 @@ 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

Captured requests could only ever be discarded by restarting the session, so a long debugging run
turned the Traffic list into a haystack ([#23](https://github.com/devconsole-android/DevConsole/issues/23)).
Both operator surfaces can now clear them.

**Version note, deliberately unresolved here:** `NetworkTransactionStore` gains an abstract
`clear()`. That interface is not documented as a host extension point and nothing outside this repo
is known to implement it, but under this file's own [policy](#versioning-and-stability-policy) a new
abstract member is source-breaking for anyone who does. It is in `sdk:network`, not `sdk:api`, so it
does not automatically read as a major. The number is left for the release decision rather than
assumed.

### Added

- **Clear captured requests**, on the device and in the browser. The in-app inspector grows a trash
action in the Observe screen's top area, shown on the Traffic tab once there is something to
discard; the dashboard's Network toolbar grows a **Clear captures** button beside the HAR and
Postman exports. Both confirm first, and both name what survives.

The two surfaces share one store, so a clear on either empties the other on its next read. Captures
are held in memory only, which is what makes this irreversible and why the confirmation is not
optional.

Evidence is deliberately spared: the tray holds materialized copies of flagged captures and
outlives the live buffer by design, so clearing never costs anyone the bug they were collecting.
Timeline events recorded for those requests are a separate store and are likewise untouched.

- **`DELETE /api/v1/network/transactions`**, backing the dashboard button. Gated like the
evidence-tray mutations rather than by an editing capability — bearer session plus `Origin` and
`X-DevConsole-CSRF`, audited as `network.clear` — because it empties this SDK's own capture buffer
and never reaches host application state. Subject to the same `network` capture-category check as
the read routes, and idempotent: clearing an already-empty store is a plain success. See
[docs/PROTOCOL_REFERENCE.md](docs/PROTOCOL_REFERENCE.md).

- **`InspectorDataSource.clearTransactions()`**, defaulting to `Unavailable` so existing adapters
keep compiling, and `InspectorAction.ClearTransactions` to reach it.

### Changed

- **`NetworkTransactionStore.clear()` is now part of the interface** rather than only of
`InMemoryNetworkTransactionStore`. The Ktor module holds its store through the interface, so the
new route could not otherwise reach it. Left abstract rather than given a no-op default: a custom
store that silently declined to clear would fail invisibly, which is worse than failing to compile.

## 1.2.4 — 2026-08-20

### Fixed
Expand Down
11 changes: 11 additions & 0 deletions docs/NETWORK_INSPECTOR.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,17 @@ detail pane showing redacted headers and body. From the detail pane you can:
export is available as an in-app action on the device — see
[DATA_INSPECTORS_AND_EXPORTS.md](DATA_INSPECTORS_AND_EXPORTS.md).

The Network page's toolbar also carries **Clear captures** (`DELETE /api/v1/network/transactions`),
which discards every captured transaction on the device after a confirmation. The same action is
available in the in-app inspector, as the trash icon in the Observe screen's top area on the Traffic
tab. Either one empties the single shared store, so a clear on the device empties the dashboard's
list too (and vice versa) on its next read.

Captures are held in memory only, so a clear cannot be undone. Anything flagged as evidence survives
it: the evidence tray stores materialized copies of flagged captures and outlives the live buffer by
design — see [EVIDENCE_AND_BUG_REPORTS.md](EVIDENCE_AND_BUG_REPORTS.md). Timeline events recorded for
those requests are a separate store and are likewise untouched.

The Overview page's network-status-distribution widget (`GET /api/v1/overview`) buckets recent
transactions by `2xx`/`3xx`/`4xx`/`5xx`/`pending` via `NetworkTransactionStore.statusDistribution()`.

Expand Down
10 changes: 10 additions & 0 deletions docs/PROTOCOL_REFERENCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,16 @@ id, if the selected transactions happen to share a dedup key; it can also make
`X-DevConsole-Export-Count` (measured before dedup) read higher than the number of `item`s that
actually end up in the Postman collection body.

`DELETE /api/v1/network/transactions` discards every captured transaction — the dashboard's "Clear
captures" toolbar button, and the counterpart of the in-app inspector's own clear action. Gated like
the evidence-tray mutations rather than by an editing capability: bearer session plus `Origin` and
`X-DevConsole-CSRF`, audited as `network.clear`, and subject to the same `network` capture-category
check as the read routes above (`CATEGORY_DISABLED` 403 when the host disabled the category). It
answers `{"status":"cleared"}` and is idempotent — clearing an already-empty store is a plain
success. Evidence is untouched: the tray holds materialized copies of flagged captures, so clearing
the live buffer never destroys collected evidence. Any outstanding pagination cursor is invalidated
by the shrink, per §4.2.

### Mocks

`GET /api/v1/mocks` (enabled flag), `POST /api/v1/mocks/disable-all` (auth), `POST
Expand Down
11 changes: 11 additions & 0 deletions sdk/full/src/main/kotlin/io/devconsole/FullInspectorDataSource.kt
Original file line number Diff line number Diff line change
Expand Up @@ -819,6 +819,17 @@ internal class FullInspectorDataSource(
return shareableFileResolver(root, relativePath)?.absolutePath
}

/**
* Ungated by capability for the same reason the exports below are: this empties the SDK's own
* capture buffer and never reaches host application state. Evidence is untouched -- `EvidenceStore`
* holds materialized copies of flagged captures (see [flagTransaction]) and outlives the buffer
* by design.
*/
override fun clearTransactions(): InspectorCommandResult {
networkTransactionStore.clear()
return InspectorCommandResult.Success(summary = "Captured requests cleared")
}

/**
* Ungated by capability: exports read already-captured, already-redacted data, the same as
* [listFiles]/[previewFile]/[listTables] above.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,8 @@ class AndroidInspectorExporterTest {
override fun find(id: String): NetworkTransaction? = null

override fun statusDistribution(): Map<String, Int> = emptyMap()

override fun clear() = Unit
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -502,6 +502,48 @@ class FullInspectorDataSourceTest {
assertTrue(source.flaggedTransactionIds().isEmpty())
}

@Test
fun `clearTransactions empties the capture store and the snapshot it feeds`() {
val store = networkStore()
recordTransaction(store, "tx-1", startedAtEpochMs = 0, completedAtEpochMs = 5)
recordTransaction(store, "tx-2", startedAtEpochMs = 10, completedAtEpochMs = 15)
val source = FullInspectorDataSource(store, MockEngine(emptyList()), configSupplier = { null })
assertEquals(2, source.snapshot().transactions.size)

val result = source.clearTransactions()

assertTrue(result is InspectorCommandResult.Success)
assertTrue(source.snapshot().transactions.isEmpty())
assertNull(store.find("tx-1"))
}

/**
* Evidence is durable and materialized at flag time -- clearing the live capture buffer must not
* take collected bug evidence with it.
*/
@Test
fun `clearTransactions leaves flagged evidence intact`() =
runTest {
val store = networkStore()
recordTransaction(store, "tx-1", startedAtEpochMs = 0, completedAtEpochMs = 5)
val evidence = FakeEvidenceStore()
val source =
FullInspectorDataSource(
store,
MockEngine(emptyList()),
configSupplier = { null },
evidenceStore = evidence,
evidenceSessionId = { "session-1" },
)
source.flagTransaction("tx-1")

source.clearTransactions()

assertTrue(source.snapshot().transactions.isEmpty())
assertEquals(setOf("tx-1"), source.flaggedTransactionIds())
assertEquals(1, evidence.items("session-1").size)
}

@Test
fun `flagTransaction surfaces AlreadyFlagged with a human-readable message instead of throwing or no-opping`() =
runTest {
Expand Down
3 changes: 2 additions & 1 deletion sdk/network/api/network.api
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ public final class io/devconsole/network/InMemoryNetworkTransactionStore : io/de
public static final field DEFAULT_MAX_TRANSACTIONS I
public fun <init> (Lio/devconsole/network/NetworkCursorCodec;I)V
public synthetic fun <init> (Lio/devconsole/network/NetworkCursorCodec;IILkotlin/jvm/internal/DefaultConstructorMarker;)V
public final fun clear ()V
public fun clear ()V
public fun find (Ljava/lang/String;)Lio/devconsole/network/NetworkTransaction;
public fun page (Lio/devconsole/network/NetworkTransactionQuery;)Lio/devconsole/network/NetworkTransactionPage;
public fun record (Lio/devconsole/network/NetworkTransaction;)V
Expand Down Expand Up @@ -551,6 +551,7 @@ public final class io/devconsole/network/NetworkTransactionRecorder$Companion {
}

public abstract interface class io/devconsole/network/NetworkTransactionStore {
public abstract fun clear ()V
public abstract fun find (Ljava/lang/String;)Lio/devconsole/network/NetworkTransaction;
public abstract fun page (Lio/devconsole/network/NetworkTransactionQuery;)Lio/devconsole/network/NetworkTransactionPage;
public abstract fun record (Lio/devconsole/network/NetworkTransaction;)V
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,15 @@ interface NetworkTransactionStore {
fun find(id: String): NetworkTransaction?

fun statusDistribution(): Map<String, Int>

/**
* Discards every stored transaction. Backs the operator-facing "clear captures" affordance on
* both the in-app inspector and the dashboard, as well as the session-rollover reset in
* `PlatformFacadeProvider`. On the interface rather than only on
* [InMemoryNetworkTransactionStore] because callers that hold a store through this type -- the
* Ktor module's `networkTransactions`, notably -- are exactly the ones that need it.
*/
fun clear()
}

/** Bounded, thread-safe transaction store for the live network inspector. */
Expand Down Expand Up @@ -133,7 +142,7 @@ class InMemoryNetworkTransactionStore(
return this
}

fun clear() =
override fun clear() =
synchronized(lock) {
transactions.clear()
storedBytes = 0
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,57 @@ class InMemoryNetworkTransactionStoreTest {
assertEquals(listOf("matching"), page.transactions.map(NetworkTransaction::id))
}

@Test
fun `clear empties the store`() {
val store = InMemoryNetworkTransactionStore(NetworkCursorCodec("network-cursor-key".encodeToByteArray()))
store.record(transaction("first", 100, "GET", "https://api.test/first", 200))
store.record(transaction("second", 200, "POST", "https://api.test/second", 201))

store.clear()

assertEquals(emptyList<NetworkTransaction>(), store.page(NetworkTransactionQuery(limit = 10)).transactions)
assertNull(store.find("first"))
assertEquals(emptyMap<String, Int>(), store.statusDistribution())
}

/**
* [InMemoryNetworkTransactionStore] prunes on a running byte total, so a clear that emptied the
* list without zeroing that total would leave the store believing it still held the cleared
* bytes -- and evict freshly recorded captures to get back under a budget nothing is using.
*/
@Test
fun `clear resets the byte budget so later records are not evicted`() {
val store =
InMemoryNetworkTransactionStore(
NetworkCursorCodec("network-cursor-key".encodeToByteArray()),
maxTransactions = 10,
).withByteCapacity(700)
val factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default()))
val bulky = { id: String ->
NetworkTransaction(
id = id,
startedAtEpochMs = 1L,
completedAtEpochMs = 2L,
capture =
factory.capture(
NetworkRequestInput(
"POST",
"https://api.test/$id",
body = "x".repeat(500).encodeToByteArray(),
contentType = "text/plain",
),
null,
),
)
}
store.record(bulky("before-clear"))

store.clear()
store.record(bulky("after-clear"))

assertEquals(listOf("after-clear"), store.page(NetworkTransactionQuery(limit = 10)).transactions.map { it.id })
}

private fun transaction(
id: String,
startedAt: Long,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1232,6 +1232,35 @@ fun Application.devConsoleModule(
}
call.respondNetworkTransactionPage(networkTransactions.page(query))
}
/**
* Discards every captured transaction -- the dashboard's "Clear" action beside the HAR and
* Postman exports, and the counterpart of the in-app inspector's own clear.
*
* Gated like the evidence-tray mutations rather than like a capability-guarded control
* route: it empties this SDK's own capture buffer and never reaches host application state.
* Evidence is deliberately left alone -- `EvidenceStore` holds materialized copies of
* flagged captures, so clearing the live buffer must not destroy collected bug evidence.
*
* Idempotent: clearing an already-empty store is a plain success, so the button never has to
* reason about whether anything is left to clear.
*/
delete("/api/v1/network/transactions") {
val session =
call.captureControlSession(
sessionAuthority,
commandAuditLog,
"network.clear",
"transactions",
) ?: return@delete
if (!categoryEnabled("network")) {
commandAuditLog.recordControlFailure(session.id, "network.clear", "transactions")
call.respondCategoryDisabled("network")
return@delete
}
networkTransactions.clear()
commandAuditLog.recordControlSuccess(session.id, "network.clear", "transactions")
call.respondText("{\"status\":\"cleared\"}", contentType = io.ktor.http.ContentType.Application.Json)
}
get("/api/v1/retained-events") {
if (sessionAuthority.bearerSession(call.request.headers[HttpHeaders.Authorization]) == null) {
call.respondText("{\"code\":\"AUTH_REQUIRED\"}", status = HttpStatusCode.Unauthorized)
Expand Down Expand Up @@ -1774,7 +1803,7 @@ fun Application.devConsoleModule(
}
post("/api/v1/evidence") {
val session =
call.evidenceControlSession(
call.captureControlSession(
sessionAuthority,
commandAuditLog,
"evidence.flag",
Expand Down Expand Up @@ -1852,7 +1881,7 @@ fun Application.devConsoleModule(
delete("/api/v1/evidence/{kind}/{id}") {
val subjectId = call.parameters["id"].orEmpty()
val session =
call.evidenceControlSession(
call.captureControlSession(
sessionAuthority,
commandAuditLog,
"evidence.unflag",
Expand All @@ -1878,7 +1907,7 @@ fun Application.devConsoleModule(
}
delete("/api/v1/evidence") {
val session =
call.evidenceControlSession(
call.captureControlSession(
sessionAuthority,
commandAuditLog,
"evidence.clear",
Expand All @@ -1896,7 +1925,7 @@ fun Application.devConsoleModule(
}
put("/api/v1/evidence/report") {
val session =
call.evidenceControlSession(
call.captureControlSession(
sessionAuthority,
commandAuditLog,
"evidence.report.save",
Expand Down Expand Up @@ -1951,7 +1980,7 @@ fun Application.devConsoleModule(
// so this route only needs to map every ScreenshotResult variant to its own response.
post("/api/v1/screenshots") {
val session =
call.evidenceControlSession(
call.captureControlSession(
sessionAuthority,
commandAuditLog,
"screenshot.capture",
Expand Down Expand Up @@ -4334,15 +4363,16 @@ private suspend fun io.ktor.server.application.ApplicationCall.composerExecution
}

/**
* Shared entry gate for every evidence-tray and screenshot mutation route: authenticated bearer
* session, then origin and CSRF. Unlike mocks/capture-rules/preferences/files/database, there is no
* separate editing capability here -- flagging evidence or capturing a screenshot never lets a
* session touch host application state, so this mirrors [isReadMutationAuthorized]'s two-stage gate
* (auth, then CSRF) rather than [mockRuleControlSession]'s three-stage one, while still auditing every
* rejection past authentication under [commandType] like every other command route.
* Shared entry gate for every mutation that touches only this SDK's own captured data -- the
* evidence tray, screenshots, and clearing the network capture buffer: authenticated bearer session,
* then origin and CSRF. Unlike mocks/capture-rules/preferences/files/database, there is no separate
* editing capability here -- flagging evidence, capturing a screenshot or discarding captures never
* lets a session touch host application state, so this mirrors [isReadMutationAuthorized]'s two-stage
* gate (auth, then CSRF) rather than [mockRuleControlSession]'s three-stage one, while still auditing
* every rejection past authentication under [commandType] like every other command route.
*/
@Suppress("ReturnCount") // One early-exit per gate stage (auth, CSRF) reads clearest.
private suspend fun io.ktor.server.application.ApplicationCall.evidenceControlSession(
private suspend fun io.ktor.server.application.ApplicationCall.captureControlSession(
sessionAuthority: SessionAuthority,
commandAuditLog: CommandAuditLog,
commandType: String,
Expand Down
Loading
Loading