Repository navigation
feat: add session.webRequest.setHeaderRules() - #53222
codebytere wants to merge 13 commits into
Conversation
…r-only webRequest listeners The IO-thread gate from #53115 sent every renderer request through the UI-thread ProxyingURLLoaderFactory as soon as the session had any webRequest listener, and the proxy itself wrapped every request in an InProgressRequest for the same reason: a listener may modify the request and re-runs on every redirect leg, so its URL filter cannot be applied up front. Two things can be decided up front though: - A request's resource type never changes across redirects, so the listeners' existing `types` filter is honored before the request reaches the UI thread: a blocking listener (onBeforeRequest, onBeforeSendHeaders, onHeadersReceived) registered with types: ['mainFrame', 'subFrame'] no longer pulls images, scripts and fetches through the main process. - onSendHeaders, onBeforeRedirect, onResponseStarted, onCompleted and onErrorOccurred cannot change anything. When only such listeners match a request's type, it goes straight to the network service and a pass-through URLLoaderClient on the IO thread reports the redirect, response and completion to api::WebRequest afterwards; the listeners get the same details objects (including onSendHeaders per redirect leg), the renderer never waits for them. InterceptState holds two resource-type masks instead of a boolean, recomputed whenever a listener is added or removed, and both the gate and the proxy's pass-through path consult them. Linux x64, page with 150 subresources from a local server while the main process is busy for 100 ms after commit: onCompleted + onErrorOccurred listeners 160 -> 55 ms (no listeners: 54 ms); fetch() round trip 0.59 -> 0.46 ms; main process CPU per request 335 -> 244 us. With onBeforeRequest / onHeadersReceived limited to frame types, subresources take the direct path as well (fetch 0.61 -> 0.42 ms, 321 -> 133 us per request); the document itself is still intercepted, so that page's load event lands at 108 ms under the same load.
…ests on the direct path
ab7be66 to
cbe4369
Compare
Apps that register an onBeforeSendHeaders listener only to attach the
same headers to every request for their own hosts (an authorization or
identification header, a modified User-Agent) pay for it with every
request taking a round trip through the main process. setHeaderRules()
declares such changes instead:
ses.webRequest.setHeaderRules([
{ urls: ['https://api.example.com/*'],
requestHeaders: { Authorization: `Bearer ${token}` } },
{ urls: ['https://*.example.com/*'], types: ['mainFrame'],
responseHeaders: { 'X-Frame-Options': null } }
])
The rules are compiled once into an immutable HeaderRules snapshot held
by the session's InterceptState. The network service already asks the
browser about each request leg through TrustedHeaderClient
(OnBeforeSendHeaders(url, headers) / OnHeadersReceived) for loaders
created with kURLLoadOptionUseHeaderClient; the IO-thread
URLLoaderFactoryGate now owns the factory's TrustedURLLoaderHeaderClient,
answers those calls itself from the snapshot for requests it sends
straight to the network, and forwards them to ProxyingURLLoaderFactory
for requests that a blocking listener or intercepted protocol routes
there; the proxy applies the same snapshot before its listeners run, so
a listener sees and can override what the rules did. Headers are set
below CORS, like onBeforeSendHeaders with "extraHeaders" today.
Rules are evaluated per network transaction and fail closed across
redirects: the names a rule set on an earlier leg are tracked per
request and removed on any leg the current rules would not set them
(different host, different type, or rules replaced mid-request), so a
credential attached for one host is never forwarded to a redirect
target outside `urls`. A rule that sets a request header must name its
hosts; <all_urls> and wildcard-only hosts are rejected for such rules.
Linux x64, 150-subresource page from a local server, main process busy
for 100 ms after commit: with an onBeforeSendHeaders listener 160 ms,
with an equivalent rule 57 ms (no listeners: 52 ms); fetch() round trip
0.70 -> 0.49 ms; main-process CPU per request 350 -> 170 us.
cbe4369 to
3327eee
Compare
…r-rules # Conflicts: # shell/browser/api/electron_api_web_request.h # shell/browser/net/proxying_url_loader_factory.cc # shell/browser/net/url_loader_factory_gate.cc # shell/browser/net/url_loader_factory_gate.h # spec/api-web-request-spec.ts # spec/fixtures/api/web-request/server.js
|
|
||
| * `urls` string[] - Array of [URL patterns](https://developer.chrome.com/docs/extensions/develop/concepts/match-patterns) | ||
| the rule applies to. A rule that sets a request header must use patterns that | ||
| name a host, such as `https://*.example.com/*`; `<all_urls>` and patterns |
There was a problem hiding this comment.
Is this a restriction enforced by Chromium internals, or is it an intentional limitation we're adding to the API? I'm curious if there would be any use-cases for people to add a header to all outgoing requests.
There was a problem hiding this comment.
good question - it's ours, not chromium's. a rule that sets a request header is usually carrying a credential, and with <all_urls> it would go to every origin the session talks to, including wherever a redirect lands; the per-leg re-evaluation in this PR exists to stop exactly that, so an unbounded pattern would undo it. removal-only rules and response-header rules do accept <all_urls>. if a case for a non-sensitive header on everything comes up we can relax it for that, i'd just rather start strict.
|
|
||
| The `listener` will be called with `listener(details)` when an error occurs. | ||
|
|
||
| #### `webRequest.setHeaderRules(rules)` |
There was a problem hiding this comment.
This design is similar to Chrome extension's declarativeNetRequest API. Do you think there's any opportunity to reuse some of its design or internals? If so, we may get features like regex substitutions or per-resource type filtering for free.
There was a problem hiding this comment.
thanks, i did look at that! the internals aren't practical to share unfortunately: DNR's matcher/ruleset lives under //extensions and is keyed to extension ids, the ExtensionRegistry and extensions' own proxying factory, so using it from a session api means either depending on the extensions layer unconditionally or extracting a large chunk of it, and the win here is the IO-thread TrustedHeaderClient path rather than the matching. per-type filtering is already in (types). the design side is more open - if we'd rather the rule shape mirror DNR's modifyHeaders action (requestHeaders: [{ header, operation: 'set' | 'remove', value }] instead of the Record<string, string | null> shorthand) i'm up for reshaping it that way for familiarity; regex substitution and redirect actions i'd keep out of this PR. which shape would you prefer?
There was a problem hiding this comment.
Findings marked 🟡 are optional suggestions and need no follow-up push.
Additional findings (outside the current diff — GitHub can't attach inline comments there):
-
🔴
shell/browser/net/proxying_url_loader_factory.cc— Header rules are silently skipped for navigations,net.fetch, workers and extension-proxied sessions unless a blocking listener also matches. That includes the documentedmainFrameresponse-rule example. Routing decides to bypass the proxy and the gate without checking whether header rules exist. Fix: make every bypass decision treat existing rules like a listener, which covers the 2 sites listed. In the pass-through branch, setkURLLoadOptionUseHeaderClientand answerOnLoaderCreatedwith a rule-applying client. Same pattern at 2 sites (proxying_url_loader_factory.cc:905, electron_browser_client.cc:1602).Why this was flagged
The gate is only created for frame subresource factories (electron_browser_client.cc:1630 skips
kNavigation). Navigation, worker-main-resource and browser-process factories such as net.fetch get a bare ProxyingURLLoaderFactory. When no blocking listener matches,InterceptState::RouteFor(url_loader_factory_gate.cc:157-168) returns kDirect, because it never looks at header rules. CreateLoaderAndStart at proxying_url_loader_factory.cc:905 then passes the request straight to the target with its options unchanged. ProxyingURLLoaderFactory::OnLoaderCreated binds a NoOpHeaderClient for unknown ids, so ContinueToBeforeSendHeaders and the response-rule code never run. Separately, electron_browser_client.cc:1602 lets the extensions WebRequestAPI proxy the factory and return early whenever!web_request->HasListener(). With an extension using webRequest loaded, neither the gate nor the Electron proxy exists, so no rule is applied to any request. The spec only covers renderer fetch() subresources, so neither case is tested.Verification: RouteFor (url_loader_factory_gate.cc:157-168) checks only WantsURL, blocking_types_ and observer_types_; it never reads header_rules_. When
route != kProxy || !web_request_->HasListener(), the request goes straight totarget_factory->CreateLoaderAndStart(..., options, ...). It never setskURLLoadOptionUseHeaderClientand never applies rules. -
🟡
shell/browser/net/url_loader_factory_gate.cc— Long-lived pages leak memory in the browser IO thread. One request id is stored per proxied or ruled request, and these entries are never erased.proxied_requests_grows on every proxied request even with no header rules set, since it is gated only on a bound header client. Fix: drop each entry when it is consumed. Erase theruled_requests_entry in OnLoaderCreated, which always runs for ruled requests because the gate setskURLLoadOptionUseHeaderClient. Stop recording proxied ids and forward any id not inruled_requests_to the interceptor; its OnLoaderCreated already binds a no-op client for unknown ids.Why this was flagged
URLLoaderFactoryGate::CreateLoaderAndStart (url_loader_factory_gate.cc:815-824) inserts
request_idintoproxied_requests_for every kProxy-routed request wheneverheader_client_is bound. It inserts intoruled_requests_for every direct request while rules exist. Neither container is ever erased: OnLoaderCreated only does find/contains, and no completion hook removes entries. The comment at :891-892 notes that ids are unique per document, but uniqueness does not bound the size. Consider an app with anonBeforeSendHeaderslistener (or an intercepted scheme) whose page polls with fetch, for example a dashboard or chat client open for days. The gate's flat_set/flat_map then grows for the life of the document. On the base branch the gate kept no per-request state. For proxied requests that are not in extraHeaders mode, OnLoaderCreated is never called at all, so erasing on lookup alone would not free them. That is why the fix also has to stop recording proxied ids.Verification: In CreateLoaderAndStart (lines 468-477) of shell/browser/net/url_loader_factory_gate.cc,
proxied_requests_.insert(request_id)runs for every kProxy-routed request, gated only onheader_client_.is_bound(). Nothing erases from them. Both containers grow for as long as the factory lives (one document). This is new in this change: the base has neither container.
| Rules apply to `http:`, `https:`, `ws:` and `wss:` requests made through the | ||
| session, including those from `net.fetch`; they do not apply to protocols | ||
| handled with `protocol.handle`. |
There was a problem hiding this comment.
🔴 Apps that set rules for ws:/wss: URLs or the webSocket type get no header changes on WebSocket handshakes, although the docs say rules apply to them. Handshakes only go through ProxyingWebSocket when WillInterceptWebSocket sees HasListener(), which ignores header rules (electron_browser_client.cc:1518). ProxyingWebSocket itself never consults header_rules() either. Fix: have WillInterceptWebSocket also return true when header rules exist, and apply them in ProxyingWebSocket's request/response header steps the same way the URL loader paths do. Otherwise, drop ws:/wss: and webSocket from the documented scope.
Why this was flagged
An app calls setHeaderRules([{urls:['wss://api.example.com/*'], requestHeaders:{Authorization:'Bearer t'}}]) with no webRequest listeners and opens new WebSocket('wss://api.example.com/') from a page. ElectronBrowserClient::WillInterceptWebSocket (electron_browser_client.cc:1503-1528) returns web_request->HasListener(), and that is false: HasListener (electron_api_web_request.cc:381-383) checks only simple_listeners_/response_listeners_. So the handshake goes straight to the network without the header. Even when a listener exists, a grep for header_rules finds no hits in shell/browser/net/proxying_websocket.cc, so the rules are never applied there. HeaderRules::Compile accepts these rules: kSchemes includes SCHEME_WS/SCHEME_WSS (header_rules.cc:20-21), and 'webSocket' is a valid type (url_loader_factory_gate.cc:105). setHeaderRules therefore succeeds without error, while docs/api/web-request.md:357-359 promises the rules apply to ws: and wss: requests. This is a new API, so the base branch has no such promise.
Verification: ElectronBrowserClient::WillInterceptWebSocket (electron_browser_client.cc:1503-1529) returns web_request->HasListener(), which ignores header_rules_. With rules set and no listeners, Electron never proxies the handshake. shell/browser/net/proxying_websocket.cc is not in the diff and has no reference to header_rules/HeaderRules.
| for (const auto& name : *injected) { | ||
| if (!set_now.contains(name)) | ||
| headers->RemoveHeader(name); | ||
| } |
There was a problem hiding this comment.
🔴 Apps whose rule overrides a header the request already carries, such as User-Agent (the PR's example), lose that header entirely after a redirect to a host the rules don't cover. Only header names are tracked in injected, so a later leg removes the name outright instead of restoring the request's own value. Fix: record each overridden header's original value (or absence) and restore it on uncovered legs, removing only values the rule injected. This covers 3 sites (header_rules.cc:192-195, url_loader_factory_gate.cc:377-379, proxying_url_loader_factory.cc:490-492).
Why this was flagged
An app calls setHeaderRules([{ urls: ['https://api.example.com/*'], requestHeaders: { 'User-Agent': 'MyApp/1.0' } }]), a use case the PR description names. A page then fetches a URL there that 302s to cdn.other.com. On leg 1, ApplyToRequest overwrites the request's existing User-Agent and adds "user-agent" to injected (header_rules.cc:184-185). On leg 2 no rule matches, so header_rules.cc:192-194 calls RemoveHeader("user-agent") on the leg's headers. The CDN request therefore goes out with no User-Agent instead of the browser default. The same happens to Accept, Accept-Language, Cookie, or any page-supplied header a rule overrides. When rules are cleared mid-request, the null-rules branches (url_loader_factory_gate.cc:377-379, proxying_url_loader_factory.cc:490-492) strip those names the same way. The spec only tests a custom X-Token header that the request never carries itself, so it does not catch this.
Verification: On the first leg, header_rules.cc:184-185 calls headers->SetHeader(name, *value) and records only the lowercased name in set_now. On the uncovered leg, lines 192-195 run if (!set_now.contains(name)) headers->RemoveHeader(name);. No original value is recorded, so the header cannot be restored and the leg goes out with the name removed completely.
There was a problem hiding this comment.
Code review found no new issues
No new issues were found in this update; 3 findings from earlier reviews are still open above.
Still open from earlier reviews (3):
- 🔴
docs/api/web-request.md:359—Apps that set rules for ws:/wss: URLs or the webSocket type get no header changes on WebSocket handshakes, although the… - 🔴
shell/browser/net/header_rules.cc:195—Apps whose rule overrides a header the request already carries, such as User-Agent (the PR's example), lose that header… - 🔴
shell/browser/net/proxying_url_loader_factory.cc:494—A header set by a rule can still reach a non-matching redirect target for net.fetch/net.request calls that a blocking l…
If you have decided not to act on one of these findings, resolve its thread (a reply alone leaves it open) and the next review stops counting it. To review this commit again now, use Re-run on its "Claude Code Review" check.
Description of Change
Follows #53204.
Adds
session.webRequest.setHeaderRules(rules)/getHeaderRules(): declarative request and response header changes that Electron applies itself on the IO thread, per network transaction, instead of anonBeforeSendHeaders/onHeadersReceivedlistener that pulls every request through the main process. An app that only listens in order to attach the same headers to requests for its own hosts (authorization or identification headers, a modifiedUser-Agent) can express that as rules and keep its renderer traffic on the direct path from #53115 / #53204.Linux x64 release, page with 150 small subresources from a local server in a separate process, median of 3 warm loads; "busy" = the main process runs 100 ms of JavaScript right after the navigation commits:
fetch()round triponBeforeSendHeaderslistener doing the same (today)onBeforeSendHeaderslistenerHow it works: the rules are compiled once into an immutable
HeaderRulessnapshot held by the session'sInterceptState. The network service already consults the browser for each request leg throughTrustedHeaderClient(OnBeforeSendHeaders(url, headers)/OnHeadersReceived) for loaders created withkURLLoadOptionUseHeaderClient; the IO-threadURLLoaderFactoryGatenow owns the factory'sTrustedURLLoaderHeaderClient, answers those calls from the snapshot for requests it sends straight to the network, and forwards them toProxyingURLLoaderFactoryfor requests a blocking listener or intercepted protocol routes there. The proxy applies the same snapshot before its listeners run, so a listener sees and can override what the rules did. Headers are set below CORS, asonBeforeSendHeadersdoes today. While rules exist every direct request carries the header-client option, which is the extra 0.07 ms perfetch()in the table (a network service to browser IO round trip, no main thread).Redirects fail closed: the header names a rule set on an earlier leg are tracked per request and removed on any leg the current rules would not set them (different host or type, or the rules were replaced mid-request), so a header attached for one host is never forwarded to a redirect target outside
urls. Chromium's own redirect handling only stripsAuthorizationcross-origin and body headers on method changes; this does not rely on it. A rule that sets a request header must name its hosts:<all_urls>and wildcard-only hosts are rejected for such rules and allowed for removal-only and response rules.The spec covers this differentially: the same redirect chains (single matching / non-matching request, same-host redirect, matching -> non-matching, matching -> non-matching -> matching, non-matching -> matching) run once with a rule and once with an equivalent
onBeforeSendHeaderslistener that strips on non-matching legs, asserted from what the server received on each leg, with identical results; plus a mid-requestsetHeaderRules(null), removal /excludeUrls/types, listener ordering, response rules as seen by the page and byonHeadersReceived, application while the main process is blocked, and validation.Checklist
npm testpasses (api-web-request-spec; protocol, session, net, webContents, subframe, webview, service worker and extensions specs locally on Linux)web-request.md,structures/header-rule.md)Release Notes
Notes: Added
session.webRequest.setHeaderRules()to set or remove request and response headers by URL pattern without routing requests through the main process.