blob: d72242c303d6d90054e225f2bf8d97c2d3793629 [file] [view]
# Browser-Side CDP Network Lifecycle Events
**Feature flag:** `network::features::kDevToolsNetworkEventsInBrowser`
(disabled by default)
**Bug:** [crbug.com/590592171](https://crbug.com/590592171)
[TOC]
## Summary
* With the flag on, the browser process builds the CDP `Network` lifecycle
events from typed Renderer Reports. Today Blink builds them.
* The connection and security fields of a response come only from the
network service. A renderer cannot supply them.
* Event names, event schemas, request IDs, and the order of the lifecycle
events do not change.
* For some renderer-reported responses, network-service metadata (connection
and security fields) changes or is absent. All other response fields stay
present. See the [case table](#case-table).
* The flag stays off until the
[conditions for default-on](#conditions-for-default-on) are met.
## Terms
| Term | Meaning |
| :---- | :---- |
| Lifecycle events | `requestWillBeSent`, `responseReceived`, `dataReceived`, `resourceChangedPriority`, `requestServedFromCache`, `loadingFinished`, `loadingFailed` |
| Renderer Report | A `blink.mojom.DevToolsNetworkEvent` with the data of one lifecycle event. A renderer sends it with `DevToolsSessionHost.ReportNetworkEvent()`. |
| Network Record | A `network.mojom.DevToolsResponseRecord` with the connection and security data of one response. The network service sends it to the browser. |
| Network-service metadata | The connection and security fields of `Network.Response` that only the network service supplies (listed below) |
| Store | A `DevToolsTrustedResponseStore` in the browser. It keeps the Network Records of one renderer process. |
| Gate | The switch in the network service that turns Network Records on for one renderer process |
| Browser-side proxy | A `URLLoaderFactory` in the browser between a renderer and the network service, for example `Fetch` interception |
**Network-service metadata fields:** `securityDetails`, `securityState` of an
HTTPS or WSS URL, `remoteIPAddress`, `remotePort`, `protocol` of an HTTP or
HTTPS URL, `alternateProtocolUsage`, `connectionReused`, and `connectionId`.
All other `Network.Response` fields (URL, status, headers, MIME type, timing)
come from the Renderer Report.
## Motivation and goals
Today Blink builds the lifecycle events and sends them as raw CDP
notifications. The browser forwards them to the client without a check of
their content. So Chromium sends TLS certificate details and connection data
to the renderer mainly to fill CDP events.
**Primary goal: data minimization.** Stop sending `SSLInfo` and connection
data to renderers. This change does not deliver that goal. It removes the
DevTools use of the data, which blocks the goal today (see
[Follow-ups](#follow-ups)).
**Goals of this change:**
1. Build the lifecycle events in the browser from Renderer Reports.
2. Take network-service metadata only from the network service.
3. Reject raw notifications from a renderer for lifecycle events and for the
browser-only `*ExtraInfo` and `EarlyHints` events.
**Threat model.** With the flag on, the browser gives one guarantee: the
network-service metadata of an event comes from a response that the network
service loaded for the same renderer process, with the request ID and the URL
that the Renderer Report names. The browser does not give more. The renderer
supplies the URL, headers, status, body, timing, and request ID of a
Renderer Report. A compromised renderer can load URL X and then send a
forged Renderer Report for X. The
event then has the real network-service metadata of X and forged content.
**Non-goals:**
* The order of `requestWillBeSentExtraInfo`, `responseReceivedExtraInfo`,
and `responseReceivedEarlyHints` relative to the lifecycle events. These
events arrive on `DevToolsObserver`, and `NetworkHandler` sends each one
when it arrives. `Network.pdl` gives no guarantee for this order.
* Other renderer `Network` events (`WebSocket`, `WebTransport`, direct
sockets, `EventSource`). They stay raw CDP notifications.
## Architecture
The renderer reports the lifecycle events of each subresource request. The
network service sends one Network Record for each response to the browser.
The browser builds each CDP event from a Renderer Report and adds
network-service metadata.
The diagram shows a subresource request. For other requests, see
[Special cases](#special-cases).
```
NetworkHandler ──gate: SetDevToolsResponseRecordsEnabled──► network service
network service ──Network Record: OnResponseRecord──► store ──────────────────┐
▼
renderer ──Renderer Report: ReportNetworkEvent──► DevToolsSession ──► NetworkHandler ──► client
▲
network service ──*ExtraInfo──► DevToolsObserver ─────────────────────────────┘
```
### Walkthrough: an HTTPS subresource with one redirect (A to B)
1. The client sends `Network.enable`. `NetworkHandler` turns the gate on for
the renderer process of the target.
2. The renderer starts the request with request ID `R` and sends a
`requestWillBeSent` Renderer Report for A.
3. `network::URLLoader` receives the redirect response of A. It sends a
Network Record for (`R`, A) to the browser. Then it sends the redirect
to the renderer.
4. The browser puts the Network Record into the store of the renderer
process.
5. The renderer follows the redirect and sends a `requestWillBeSent`
Renderer Report for B with the redirect response of A. The browser finds
the Network Record of (`R`, A), adds its network-service metadata, and
sends the CDP event.
6. `URLLoader` receives the response of B. It sends a Network Record for
(`R`, B), then the response to the renderer.
7. The renderer sends a `responseReceived` Renderer Report. The browser
finds the Network Record of (`R`, B) and sends the CDP event. The
Renderer Reports for `dataReceived` and `loadingFinished` need no
Network Record.
The Network Record of step 3 and the Renderer Report of step 5 use different
pipes. See [No wait for a Network Record](#no-wait-for-a-network-record).
### Network Record path
* **Content:** SSL info, certificate status, remote endpoint, ALPN protocol,
HTTP version, connection ID, connection reuse, and alternate protocol
usage. `CorsURLLoader` does not change.
* **When:** `URLLoader` sends one Network Record for each redirect response
and one for the final response (also for the empty response of a request
that ORB blocks). It sends the Network Record before it sends the
response to its client.
* **Gate:** Network Records are off by default, so a closed DevTools has no
cost. Only the browser can turn them on. It does this when a session
enables the `Network` domain for a target, and when such a target moves
to a different renderer process. It turns them off when the last such
session of the process goes away. The call is one-way, so
`Network.enable` does not wait for it. A response that the network
service handles before the call arrives has no Network Record.
* **Pipe:** The network service sends the Network Records of all processes
on one `DevToolsResponseRecordSink` pipe. After a network service
restart, the browser binds a new pipe and sends the gate state again.
* **Store:** The browser has one store for each renderer process whose gate
is on. `URLLoader` knows the process (`URLLoaderFactoryParams::process_id`)
and not the DevTools session. Frames and workers of one process also
share the `MemoryCache` of Blink, so they share the Network Records. The
browser drops the store when the gate goes off.
* **Key:** Inside a store, the key of a Network Record is the request ID
and the URL without the fragment. The comparison does no other
normalization.
* **Limit:** A Network Record stays in the store after its first use,
because a later memory cache hit and other sessions of the process read
it. A store keeps 1,000 Network Records and removes the least recently
used one first.
Known limits of the store:
* A redirect chain can visit the same URL two times. The later Network
Record replaces the earlier one, so the event for the first hop can
receive the connection and security metadata of the second hop.
* A renderer can remove the Network Records of its process from the store
with more than 1,000 responses. A long-lived page has the same result.
The affected renderer-reported events omit network-service metadata.
### Renderer Report path
* **What Blink reports:** Each lifecycle event of each request that it
reports today. This includes network loads, memory cache hits, requests
that a service worker controls, `blob:` and `data:` URLs, worklet
requests, prefetches, and requests that Blink blocks before they start.
* **Order:** A Renderer Report uses the same `DevToolsSessionHost` pipe as
the `Page.*` and `Runtime.*` notifications. The browser sends the CDP
event when the Renderer Report arrives. So the order of the events does
not change.
* **No connection data:** A Renderer Report has no field for SSL info,
certificate status, remote endpoint, or ALPN protocol. It has one
boolean, `security_state_unknown`. It applies only to a URL that is not
HTTPS or WSS, and it makes `securityState` `unknown`, as Blink does
today.
* **Other data:** Timestamps, headers, post data (within `maxPostDataSize`),
chunk sizes, the completion result, service worker timing and router
info, and `adProvenance` come from the Renderer Report. The browser
sanitizes the strings.
* **Lookup:** For a response or a redirect response, `NetworkHandler` looks
for the Network Record with the request ID and the URL of the Renderer
Report in its per-process store. Frame, dedicated worker, shared worker,
service worker, and worklet targets have a `NetworkHandler`. If a session
has no `NetworkHandler`, `DevToolsSession::ReportNetworkEvent` builds its
CDP events via `NetworkHandler::EmitRendererReportedNetworkEvent()` with
a null store.
### No wait for a Network Record
The browser receives Network Records and Renderer Reports on its UI thread,
on two pipes. Mojo gives no order between two pipes. A Network Record takes
one hop to the browser. The response and its Renderer Report take two hops
through the renderer. So the Network Record usually arrives first.
When a Renderer Report arrives first, the browser sends the event without
network-service metadata. All other response fields (URL, status, headers,
timing) stay present. It does not hold the event, and it does not send a
second event when the Network Record arrives. The Network Record stays in
the store for a later memory cache hit.
### Enforcement
With the flag on, `DevToolsSession` kills a renderer
(`RFH_INCONSISTENT_DEVTOOLS_MESSAGE`) that sends a lifecycle event,
`requestWillBeSentExtraInfo`, `responseReceivedExtraInfo`, or
`responseReceivedEarlyHints` as a raw CDP notification. Blink has no valid
sender of those three `*ExtraInfo` and `EarlyHints` notifications. This
applies to the sessions of all renderer targets.
### Request IDs
This design does not change who makes a request ID.
| Request | Who makes the ID | Form |
| :---- | :---- | :---- |
| Subresource of a frame or a worker | Renderer | `<process id>.<counter>` |
| Navigation, worker main script | Browser | DevTools token |
| CORS preflight | Network service | Unguessable token |
| Keepalive load in the browser | Browser | Unguessable token |
The renderer sends the ID of a subresource to the network service, so the key
of a Network Record is not trusted. The content of a Network Record is
trusted. The URL in the key stops a renderer from attaching the Network
Record of one URL to a different URL.
## Special cases
* **Navigation:** `NavigationRequest` builds `requestWillBeSent`,
`responseReceived`, and the pre-commit `loadingFailed` in the browser from
the trusted response head, as it does today. For an OOPIF it sends them
to the pre-commit target. The renderer reports the post-commit
`dataReceived`, `loadingFinished`, and `loadingFailed`. These need no
Network Record.
* **Other browser-reported requests:** CORS preflights, keepalive and beacon
loads, and signed exchange certificates do not change.
* **Worker main script:** The browser builds `requestWillBeSent` (and the
failure events when the fetch fails in the browser). On success, the
worker renderer reports the other events. Dedicated and shared workers
fetch the main script before the worker target enables `Network`.
Installing service workers fetch it with a browser-process
`URLLoaderFactory` (`kBrowserProcessId`). When a DevTools root session
is active, the browser records the trusted `URLResponseHead` metadata of
HTTP(S) worker main scripts into a bounded store: one record for each
redirect response and one for the final response. It skips responses
fetched via a service worker. `NetworkHandler` reads this store as a
fallback only when the request ID matches its DevTools token and the
response is not a memory cache hit. The browser clears this store when
the last handler turns its gate off.
* **Memory cache hit:** The Renderer Report names the request ID of the
request that loaded the resource. `NetworkHandler` uses that Network
Record only when the URLs are equal.
* **Service worker:** A response from `respondWith()` has no Network Record
with the request ID of the Renderer Report. A network fallback uses that
request ID, so it has a Network Record.
* **Service worker static routing race:** A rule with
`race-network-and-fetch-handler` or `race-network-and-cache` is
different. The renderer starts a network load with the request ID and
the URL of the request, at the same time as the fetch event or the cache
lookup. That load can make a Network Record also when the fetch handler
or the cache wins the race. `fromServiceWorker` is `true` for the two
results, so it does not show which response won.
## Client-observable effects (flag on)
With the flag off, nothing changes. With the flag on, these items change:
* **Network-service metadata:** Only renderer-reported responses use
Network Records. Browser-reported requests (navigations, CORS preflights,
keepalive loads) do not change. A Network Record is absent mainly for
renderer-only responses that did not use the network service, plus the
edge cases in the table below. In those cases, only the network-service
metadata is omitted, and all other response fields come from the Renderer
Report. For normal network loads, the values are the same as today. See
the [case table](#case-table).
* **Header order:** `Network.Headers` is a JSON object. The browser writes
its keys in sorted order. Today the order is that of the header map of
Blink. The merge of duplicate headers and the case of the names do not
change.
All other fields, the event order, the targets that get each event, the
`dataReceived` chunks, the timestamps, `Network.getResponseBody`,
`Network.streamResourceContent`, and durable messages do not change.
### Case table
This table shows how **network-service metadata** changes for an HTTPS
response when the flag is on. All other `Network.Response` fields (URL,
status, headers, MIME type, timing) always come from the Renderer Report and
do not change.
When a cell says **All fields omitted**, `securityDetails`, `remoteIPAddress`,
`remotePort`, `protocol`, and `alternateProtocolUsage` are absent from the
event, `securityState` is `unknown`, `connectionReused` is `false`, and
`connectionId` is `0`. A client cannot tell those last two values from real
connection values.
| Case | Today (flag off) | With flag on | Plan |
| :---- | :---- | :---- | :---- |
| Response after the first redirect of a chain | `securityDetails` absent; `securityState` is `unknown` | All fields present (improvement) | Keep (improvement) |
| Renderer Report arrives before its Network Record (race) ‡ | All fields present | All fields omitted | [Condition 1](#conditions-for-default-on) (add wait or verify rate) |
| Response in flight during `Network.enable` or process switch † | All fields present | All fields omitted | Accepted |
| Memory cache hit of a response loaded before `Network.enable` | `remoteIPAddress`, `remotePort`, `protocol` present; `securityDetails` absent | All fields omitted | Accepted |
| Memory cache hit after the store evicted the Network Record ‡ | All fields present | All fields omitted | Accepted |
| Service worker `respondWith()` response | Only `protocol` present | All fields omitted | [Follow-up](#follow-ups) (`protocol` fallback) |
| Service worker static routing race that the network wins | All fields present | All fields present | Keep |
| Service worker static routing race that the fetch handler wins, network response not yet received | Only `protocol` present | All fields omitted | [Follow-up](#follow-ups) (`protocol` fallback) |
| Service worker static routing race that the fetch handler or the cache wins, after the Network Record of the network load arrived † | Only `protocol` present | All fields present (copied from the network load that lost) | [Condition 2](#conditions-for-default-on) (must fix) |
| `Fetch.fulfillRequest` at the request stage | Only `protocol` present | All fields omitted | [Follow-up](#follow-ups) (`protocol` fallback) |
| `Fetch.fulfillRequest` at the response stage | Only `protocol` present | All fields present (copied from the replaced network response) | [Condition 2](#conditions-for-default-on) (must fix) |
| Request whose URL a `Fetch` client changed (`Fetch.continueRequest`) | All fields present | All fields omitted | [Condition 2](#conditions-for-default-on) (must fix) |
| Response created by a non-`Fetch` browser-side proxy without a network load † | Fields set by the proxy | All fields omitted | Accepted |
| Response from the `NetworkContext` prefetch cache † | Fields of the stored response | All fields omitted | Accepted |
| Hit in the renderer-accessible HTTP cache (`kRendererAccessibleHttpCache`) † | Fields of the stored response | All fields omitted | Accepted |
Web tests in `http/tests/inspector-protocol/network/lifecycle-events-*` cover
all rows without a mark. Rows marked ‡ are covered by C++ unit tests
(`NetworkHandlerRendererReportTest` and `DevToolsTrustedResponseStoreTest`).
Rows marked † come from reading the code and have no test.
Notes on the rows marked †:
* **Static routing race, wrong metadata:** This needs the Network Record
of the losing load to arrive before the Renderer Report of the winning
response. The renderer cancels the losing load, so the time window is
small, and a test cannot make it reliably. The "Today" value is the
value of the tested fetch handler row.
* **`NetworkContext` prefetch cache:** `NetworkContext::Prefetch()` loads
the response with `kBrowserProcessId` and without a DevTools request ID.
The cache then serves the response without a new `URLLoader`. This is
not `<link rel=prefetch>`: that load uses the HTTP cache, a test covers
it, and its fields do not change.
* **Renderer-accessible HTTP cache:** The renderer reads the cached
response directly, without a `URLLoader`. The hit has no
`original_request_id`, and a different process can be the one that
loaded the response. So the memory cache lookup cannot find a Network
Record. This loss is accepted: the primary goal needs this cache to
stop storing `SSLInfo` (see [Follow-ups](#follow-ups)).
One more case is not verified:
* Any other renderer-reported load through a browser-process
`URLLoaderFactory` (`kBrowserProcessId`) has no Network Record (worker
main scripts use the browser-side worker record store instead). The
factories for frames, isolated worlds, prefetches, dedicated and shared
workers, worklets, and Early Hints preloads use the renderer process.
## Alternatives and trade-offs
* **Wait for the Network Record with a boolean marker.** Rejected. The
network service sets a boolean in the response head when it sends a
Network Record, and the browser holds the events of a marked response
until the record arrives. A boolean cannot tell "the record is not here
yet" from "the record is not coming". The second case occurs when the
store evicted the record before the Renderer Report arrived (for
example, the renderer was at a breakpoint), when the gate went off and
on during the load, and when `Fetch.continueRequest` changed the URL.
The browser then holds the events of the request with no end, or it
needs a timer. The [sequence number](#sequence-number-of-a-network-record)
replaces this design.
* **Network Records on the `DevToolsObserver` pipes.** Rejected. A Network
Record must reach all targets of a process for memory cache hits. One
pipe and a store for each process give that.
* **The network service reports the lifecycle events.** Rejected.
`CorsURLLoader` does not see all requests: an extension can block or
redirect a request, and a cache can serve it. Only the renderer knows why
it canceled a load. The renderer also selects its reporter, so this does
not protect the URL, headers, or status.
## Conditions for default-on
1. **Race:** Add the [sequence number](#sequence-number-of-a-network-record)
and the wait that it makes possible. After that, a Renderer Report that
arrives before its Network Record does not lose network-service
metadata.
2. **Metadata of the wrong load:** An event must not get the
network-service metadata of a load that did not supply its response. The
known cases are `Fetch.fulfillRequest` at the response stage, and a
service worker static routing race that the fetch handler or the cache
wins. The sequence number fixes these cases. Also,
`Fetch.continueRequest` with a changed URL must keep the metadata of the
loaded response. The sequence number does not fix that case, because the
URL check stays.
3. **Request ID check:** Reject a Renderer Report whose request ID the
renderer cannot own. The valid IDs are `<own process id>.<counter>`, the
ID of a navigation of its frame, and the ID of its worker main script.
4. **Measurements:** The memory of the stores, and the UI thread cost of
building each event in the browser, mainly `dataReceived`. A store must
not stay after its use. One known case has no fix in this change: the
store of a renderer process that crashed stays until the target reloads
or the client detaches.
5. **Enforcement rollout:** Report a raw lifecycle, `*ExtraInfo`, or
`EarlyHints` notification from a renderer with `DumpWithoutCrashing`
first. Kill the renderer after the reports show no valid sender.
### Sequence number of a Network Record
This mechanism is not in this change. Conditions 1 and 2 require it.
* **Number:** The network service gives each Network Record a sequence
number. The numbers increase on the one record pipe, and 0 means "no
record". The network service writes the number into the Network Record
and into the response head that goes to its client
(`URLResponseHead` has a field of this type already:
`emitted_extra_info`).
* **Report:** Blink copies the number of the response head into the
Renderer Report of the response.
* **Lookup:** The browser uses a Network Record only when its number is
equal to the number of the Renderer Report. The request ID and the URL
must be equal also, as today.
* **Wait:** The browser keeps the highest number that arrived on the
record pipe. Records arrive in the order of their numbers. So for a
Renderer Report with number N:
* N is 0: no record exists. The browser sends the event immediately.
* N is not more than the highest number: the record arrived. It is in
the store, or the store evicted it, or the browser dropped it
because the process had no store at that time. The browser sends
the event immediately.
* N is more than the highest number: the record is on the pipe. The
browser holds the events of this request until number N arrives or
the pipe closes.
No timer and no flush message are necessary. Held events can arrive
after later `Page.*` and `Runtime.*` messages.
* **Responses that are not from the recorded load:** A response that a
`Fetch` client fulfills, and a response from a service worker fetch
handler or from a cache, have number 0 or the number of a different
load. So they do not get the Network Record of the load that lost.
`SanitizeResponseHeadForFetchHandler` must remove the number from the
response head that goes to a fetch handler.
* **Memory cache hit:** The cached response head keeps the number of the
load that made it. That number is not more than the highest number, so
the event does not wait.
* **Trust:** The number in a Renderer Report comes from the renderer, as
the request ID does. It is a key and not a proof. The browser looks only
in the store of the reporting process, and it keeps the URL check. A
false number can delay only the events of the renderer that sent it,
until the record pipe delivers that number.
* **Cost:** A field in `URLResponseHead` and in the Network Record, the
plumbing through Blink, and a bounded queue of held events for each
request.
## Follow-ups
* **Strip `SSLInfo` from the `URLResponseHead` that goes to renderers.** This
fixes [b/553150292](https://issuetracker.google.com/553150292). A code
search finds no reader of the content of `SSLInfo` in Blink outside the
inspector. Blink also reads `cert_status` and whether `SSLInfo` exists.
The remote endpoint and the ALPN protocol have other readers in Blink,
for example Resource Timing `nextHopProtocol`. The follow-up must cover
the renderer-accessible HTTP cache also:
`MaybeCreateHttpResponseInfoForRendererAccessibleCache()` in
`services/network/cors/cors_url_loader.cc` copies `SSLInfo` into a cache
that renderers read.
* **Move subresource `Network.getCertificate` to the browser.** Serve the
certificate from the store.
* **Take `protocol` from the Renderer Report when no Network Record
exists.** The value is web-exposed and has the trust level of the
headers. This fixes the `Only protocol present` rows of the case table
(adopting it requires updating the Summary and the `Network-service
metadata` definition to allow a renderer-supplied `protocol` fallback).
* **Add the redirect hop to the key of a Network Record.** This removes the
limit for a chain that has the same URL two times.
* **Move request `postData` capture to the network service.**
* **Reject all raw `Network.*` notifications from a renderer.** This needs
Renderer Reports for the other renderer `Network` events.
* **Send the `*ExtraInfo` events of worker subresources to the worker
target.** Today a dedicated worker gets them on the target of its frame,
and a shared worker gets none.