Skip to content

feat: add session.webRequest.setHeaderRules() - #53222

Open
codebytere wants to merge 13 commits into
mainfrom
feat/webrequest-header-rules
Open

codebytere wants to merge 13 commits into
mainfrom
feat/webrequest-header-rules

Conversation

@codebytere

@codebytere codebytere commented Aug 27, 2026 •

Copy link
Copy Markdown
Member

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 an onBeforeSendHeaders / onHeadersReceived listener 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 modified User-Agent) can express that as rules and keep its renderer traffic on the direct path from #53115 / #53204.

session.defaultSession.webRequest.setHeaderRules([
  { urls: ['https://api.example.com/*'], requestHeaders: { Authorization: `Bearer ${token}` } },
  { urls: ['https://*.example.com/*'], types: ['mainFrame'], responseHeaders: { 'X-Frame-Options': null } }
])

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:

session configuration page, idle page, busy fetch() round trip main-process CPU per request
no listeners, no rules 45 ms 52 ms 0.42 ms 136 µs
one request-header rule matching every request 56 ms 57 ms 0.49 ms 164 µs
onBeforeSendHeaders listener doing the same (today) 50 ms 162 ms 0.70 ms 332 µs
the rule plus an onBeforeSendHeaders listener 56 ms 159 ms 0.75 ms 335 µs

How it works: the rules are compiled once into an immutable HeaderRules snapshot held by the session's InterceptState. The network service already consults the browser for 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 from the snapshot for requests it sends straight to the network, and forwards them to ProxyingURLLoaderFactory for 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, as onBeforeSendHeaders does today. While rules exist every direct request carries the header-client option, which is the extra 0.07 ms per fetch() 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 strips Authorization cross-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 onBeforeSendHeaders listener that strips on non-matching legs, asserted from what the server received on each leg, with identical results; plus a mid-request setHeaderRules(null), removal / excludeUrls / types, listener ordering, response rules as seen by the page and by onHeadersReceived, application while the main process is blocked, and validation.

Checklist

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.

codebytere and others added 4 commits August 26, 2026 17:45
…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.
@codebytere codebytere added the semver/minor backwards-compatible functionality label Aug 27, 2026
@electron-cation electron-cation Bot added the new-pr 🌱 PR opened recently label Aug 27, 2026
@codebytere
codebytere changed the base branch from main to perf/webrequest-typed-observers August 27, 2026 08:38
@codebytere
codebytere force-pushed the feat/webrequest-header-rules branch 2 times, most recently from ab7be66 to cbe4369 Compare August 27, 2026 10:43
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.
@codebytere
codebytere force-pushed the feat/webrequest-header-rules branch from cbe4369 to 3327eee Compare August 27, 2026 10:52
Base automatically changed from perf/webrequest-typed-observers to main August 27, 2026 21:21
…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
@codebytere
codebytere marked this pull request as ready for review August 28, 2026 16:26
@codebytere codebytere added target/43-x-y PR should also be added to the "43-x-y" branch. target/44-x-y PR should also be added to the "44-x-y" branch. target/45-x-y PR should also be added to the "45-x-y" branch. and removed target/43-x-y PR should also be added to the "43-x-y" branch. labels Aug 28, 2026

* `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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread docs/api/web-request.md Resolved
Comment thread docs/api/web-request.md

The `listener` will be called with `listener(details)` when an error occurs.

#### `webRequest.setHeaderRules(rules)`

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@codebytere codebytere Sep 10, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

@electron-cation electron-cation Bot removed the new-pr 🌱 PR opened recently label Sep 4, 2026

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 documented mainFrame response-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, set kURLLoadOptionUseHeaderClient and answer OnLoaderCreated with 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 to target_factory->CreateLoaderAndStart(..., options, ...). It never sets kURLLoadOptionUseHeaderClient and 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 the ruled_requests_ entry in OnLoaderCreated, which always runs for ruled requests because the gate sets kURLLoadOptionUseHeaderClient. Stop recording proxied ids and forward any id not in ruled_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_id into proxied_requests_ for every kProxy-routed request whenever header_client_ is bound. It inserts into ruled_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 an onBeforeSendHeaders listener (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 on header_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.

Comment thread docs/api/web-request.md
Comment on lines +357 to +359
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`.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 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.

Comment on lines +192 to +195
for (const auto& name : *injected) {
if (!set_now.contains(name))
headers->RemoveHeader(name);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 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.

@github-actions github-actions Bot added the target/46-x-y PR should also be added to the "46-x-y" branch. label Oct 22, 2026

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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):

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.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

api-review/requested 🗳 semver/minor backwards-compatible functionality target/44-x-y PR should also be added to the "44-x-y" branch. target/45-x-y PR should also be added to the "45-x-y" branch. target/46-x-y PR should also be added to the "46-x-y" branch.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants