Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: service worker preload scripts for improved extensions support #44411

Merged
merged 3 commits into from
Jan 31, 2025

Conversation

samuelmaddock
Copy link
Member

@samuelmaddock samuelmaddock commented Oct 26, 2024

Description of Change

Implements RFC #8 which aims to allow Electron applications to support additional Chrome Extension APIs. Extension background service workers can be modified using preload scripts.

Tip

I recommend reviewing by commit. I've split up the work into logical commits to make reading it more manageable.

Todo

Backports

Post-merge

Follow up

Documentation

  • Design of V8 bindings - Overview of V8 isolates, contexts, and worlds.
  • ShadowRealms explainer - Preload realms are based on shadow realms. Essentially they can be thought of as a minimal JS context which Blink is aware of.
  • Service workers - Describes chromium's internal implementation. Notably, ServiceWorkerVersion and ServiceWorkerHost are relevant for understanding ServiceWorkerMain in this PR.

Overview

  • Creates a new "preload realm" v8::Context in renderer worker threads to allow secure interaction with service worker contexts.
  • Adds IPC capabilities to ServiceWorkerMain.

Service worker IPCs

ServiceWorkerMain.ipc matches the implementation of IpcMain to enable IPC with the renderer process service worker thread. IPCs sent from the render worker threads are dispatched on Session; currently only handling service worker IPCs.

ipcMainInternal now handles IPCs from both web frames and service workers. To differentiate the two, an IPC event has a type of either 'frame' or 'service-worker'.

flowchart TD
  PreloadRealm[Preload Realm / Service Worker] --> IPCSend;
  IsolatedWorld[Isolated World / Frame] --> IPCSend;

  IPCSend["ipcRenderer.send(channel, ...)"] --> IPCRenderFrame;
  IPCSend --> IPCServiceWorker;

  IPCServiceWorker --> ElectronApiSWIPCHandlerImpl;
  ElectronApiSWIPCHandlerImpl --> Session;
  Session --> ServiceWorkerMain;

  IPCRenderFrame --> ElectronApiIPCHandlerImpl;
  ElectronApiIPCHandlerImpl --> WebContents;

  classDef proposed fill:darkgreen;
  class PreloadRealm,IPCServiceWorker,ElectronApiSWIPCHandlerImpl,Session,ServiceWorkerMain proposed;
Loading

Architecture Flow

As a starting point for reviewing, consider some of the flows this feature implements.

// Register preload script
Session::RegisterPreloadScript(preload_script)
 └── Appends to SessionPreferences::preload_scripts_

// Initialize preload realm v8::Context
ElectronSandboxedRendererClient::WillEvaluateServiceWorkerOnWorkerThread()
 ├── preload_realm::OnCreatePreloadableV8Context()
 └── PreloadRealmLifetimeController::RunInitScript()

// Bind Mojo receiver for mojom::ElectronApiIPC in main process
(1) ElectronBrowserClient::RegisterAssociatedInterfaceBindersForServiceWorker()
 └── Add interface for mojom::ElectronApiIPC
(2) ElectronApiSWIPCHandlerImpl::BindReceiver()
 └── Init ElectronApiSWIPCHandlerImpl()

// Bind Mojo remote for mojom::ElectronApiIPC in renderer process
electron::IPCServiceWorker::IPCServiceWorker()
 ├── blink::WebServiceWorkerContextProxy->GetRemoteAssociatedInterface()
 └── Binds to mojom::ElectronApiIPC

// Bind Mojo receiver for mojom::ElectronRenderer in renderer process
ElectronSandboxedRendererClient::WillEvaluateServiceWorkerOnWorkerThread()
 ├── new ServiceWorkerData()
 ├── blink::WebServiceWorkerContextProxy->GetRemoteAssociatedInterface()
 └── Binds to mojom::ElectronRenderer

// Send IPC from renderer worker thread to main process
electron::IPCServiceWorker::SendMessage()
 │   // renderer → main
 ├── ElectronApiSWIPCHandlerImpl::Message()
 ├── Session::Message() inherited from IpcDispatcher::Message()
 │   // enters JavaScript
 ├── session.on('-ipc-message')
 ├── ServiceWorkerMain.ipc.on(channel, listener)
 └── listener()

// Send IPC from main process to renderer worker thread
electron::ServiceWorkerMain::Send()
 │   // main → renderer
 ├── ServiceWorkerData::Message()
 ├── ipc_native::EmitIPCEvent()
 │   // enters JavaScript
 ├── ipcNative.onMessage()
 └── ipcRenderer.emit(channel)

Checklist

Release Notes

Notes:

  • Added support for service worker preload scripts.

@samuelmaddock samuelmaddock added the semver/major incompatible API changes label Oct 26, 2024
@samuelmaddock samuelmaddock requested review from a team as code owners October 26, 2024 20:19
@electron-cation electron-cation bot added api-review/requested 🗳 new-pr 🌱 PR opened in the last 24 hours labels Oct 26, 2024
@samuelmaddock samuelmaddock added semver/minor backwards-compatible functionality no-backport and removed semver/major incompatible API changes labels Oct 26, 2024
@electron-cation electron-cation bot removed the new-pr 🌱 PR opened in the last 24 hours label Nov 2, 2024
Copy link
Member

@MarshallOfSound MarshallOfSound left a comment

Choose a reason for hiding this comment

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

Let's talk more about evaluateInMainWorld. Making new functions that allow evaluation of strings directly contravenes web security standards and the original purpose of the context bridge. It will expose a giant security footgun and I'm a strong -1 on exposing such a feature.

I'd love to understand the motivation / usecase and discuss with the Security WG (cc @electron/wg-security) how to solve those use-cases with an API that isn't such a footgun.

@samuelmaddock
Copy link
Member Author

samuelmaddock commented Nov 5, 2024

@MarshallOfSound the goal with evaluateInMainWorld is to provide equivalent functionality to webFrame.executeJavaScript(code) (reference in RFC).

For my particular use case, I'd like to overwrite extension APIs such as chrome.action. Here's a relatively simple example.

const { ipcRenderer, contextBridge } = require('electron');

// Expose setBadgeText API
contextBridge.exposeInMainWorld('electron', {
  setBadgeText: (text) => ipcRenderer.send('action.setBadgeText', text)
});

// Overwrite extension API to provide custom functionality
contextBridge.evaluateInMainWorld(`(function () {
  chrome.action.setBadgeText = (text) => {
    electron.setBadgeText(text);
  };
}());`);

A potential alternative might be to accept functions. This is similar to what's offered by chrome.scripting APIs.

function overrideActionApi () {
  chrome.action.setBadgeText = (text) => {
    electron.setBadgeText(text);
  };
}

contextBridge.evaluateInMainWorld({
  func: overrideActionApi,
  args: []
});

If this method existing on contextBridge is a problem, I'm open to introducing a renderer top-level module (worker|serviceWorker|preloadRealm).executeJavaScript instead.

@MarshallOfSound
Copy link
Member

webFrame.executeJavaScript is also a foot gun, it's an API that wouldn't land nowadays and if we could, we'd remove it. I wouldn't use it as an example

It sounds like what you want is support for overriding existing APIs from contextBridge which is a thing it supports internally but isn't exposed via API

@samuelmaddock
Copy link
Member Author

It sounds like what you want is support for overriding existing APIs from contextBridge which is a thing it supports internally but isn't exposed via API

@MarshallOfSound The example I provided is limited. However, I do have use cases which require additional logic where providing a complete function would be necessary. For example, some extension APIs require serializing arguments such as action.setIcon.

Additionally, the v8::Context provided in this implementation is based on ShadowRealms. These lack most DOM APIs, but could be partially restored by evaluating a method.

// Polyfill setTimeout in ShadowRealmGlobalScope
function setTimeoutAsync (delay) {
  return contextBridge.evaluateInMainWorld({
    func: function mainWorldFunc (delay) {
      return new Promise((resolve) => setTimeout(resolve, delay));
    },
    args: [delay]
  });
}

@MarshallOfSound
Copy link
Member

However, I do have use cases which require additional logic where providing a complete function would be necessary. For example, some extension APIs require serializing arguments such as action.setIcon.

In this case adding support for zero-copy context bridge transfer of ImageData should be the path forward. The V8 serializer already supports ImageData afaics so there is at least copy-based support already

Additionally, the v8::Context provided in this implementation is based on ShadowRealms. These lack most DOM APIs, but could be partially restored by evaluating a method.

I don't think this is a good enough usecase to justify a security footgun, the web knows it, chrome knows it, passing strings around to be evalled is just a nightmare. Someones gonna do something silly like window.foo('${userInput}'). Passing an actual Function in plus Args[] is maybe more acceptable, but in an ideal world we don't build an API that deliberately bypasses web security

@samuelmaddock
Copy link
Member Author

Passing an actual Function in plus Args[] is maybe more acceptable, but in an ideal world we don't build an API that deliberately bypasses web security

@MarshallOfSound If I refactor this API to accept a Function and Args[], will that be acceptable? My current solution works with this approach.

@MarshallOfSound
Copy link
Member

@MarshallOfSound If I refactor this API to accept a Function and Args[], will that be acceptable? My current solution works with this approach.

Ideally we find a way to avoid this APi surface entirely, does the overrideGlobalPropertyFromIsolatedWorld internal API + ImageData being copy-able not solve your usecase without the need for JS execution?

@samuelmaddock
Copy link
Member Author

Ideally we find a way to avoid this APi surface entirely, does the overrideGlobalPropertyFromIsolatedWorld internal API + ImageData being copy-able not solve your usecase without the need for JS execution?

My current constraints:

  • Read deeply-nested properties from the main world
  • Override deeply-nested properties in the main world
  • Invoke deeply-nested function properties in the main world and retrieve the result
  • Serialize ImageData for IPC to the main process

There's also the issue of future unknowns. JS execution will allow the flexibility to solve varied problems with a small API surface.

I'm not sure I fully understand the footgun argument against JS execution (outside of eval strings). Electron provides application developers with full control over a chromium browser environment through JS APIs, and this seems to take away from that level of control. This is a fairly common API provided in projects such as Chrome DevTools Protocol, Chrome Extensions, Puppeteer/Playwright, Selenium, and node's vm module.

@MarshallOfSound
Copy link
Member

I'm not sure I fully understand the footgun argument against JS execution (outside of eval strings)

Let me clarify my stance

  • Eval of strings === hard no from me on any additional API surface that exposed this capability and we should be working to minimize, deprecate and remove existing instances of this
  • Safe stringification of functions + serialized argument passing === the acceptable alternative to eval of strings, this is what existing APIs should be ported to
  • Context Bridge capabilities, either exposing / overriding existing objects, deep properties === ideal, we should be doing this and recommending this over the other two alternatives

To give a path forward given the constraints noted above (thanks for those, gives a clear picture of what is needed)

  • Update the API to take a function and stringify it safely using FunctionProtoToString()
  • Add a test to ensure user provided toString methods either on functions or on the function prototype don't affect the evaluation
  • If possible reuse chrome extension evaluation logic for this (they support functions iirc)
  • Ensure return values and arguments go over the ctx bridge

Docs for the function thing could be fun, but at least technically that's the way forward IMO

@samuelmaddock samuelmaddock force-pushed the feat/preload-realm branch 2 times, most recently from 4791bda to c6164aa Compare November 9, 2024 01:37
@samuelmaddock
Copy link
Member Author

samuelmaddock commented Nov 9, 2024

I've refactored contextBridge.evaluateInMainWorld to now accept { func: Function, args: any[] } in c6164aa. This is based on logic from Chrome extension's chrome.scripting.executeScript.

Tests to guarantee return values go through the context bridge reuse the logic from our webFrame.executeJavaScript world safe test. The internals of evaluateInMainWorld are shared with exposeInMainWorld.

cc @MarshallOfSound

chrome.scripting.executeScript internals
contextBridge.evaluateInMainWorld(script) types

The types are currently using any. We'll need to modify our type definition generator to better support adding generics here. Given the API being marked as Experimental, we can update this in a follow up PR to prevent blocking this PR.

interface EvaluationScript {
  /**
   * A JavaScript function to evaluate. This function will be serialized which means
   * that any bound parameters and execution context will be lost.
   */
  func: (...args: any[]) => any;
  /**
   * The arguments to pass to the provided function. These arguments must be
   * JSON-serializable.
   */
  args?: any[];
}

interface ContextBridge {
  evaluateInMainWorld(evaluationScript: EvaluationScript): any;
}

@samuelmaddock samuelmaddock added the target/35-x-y PR should also be added to the "35-x-y" branch. label Jan 28, 2025
Copy link
Member

@erickzhao erickzhao left a comment

Choose a reason for hiding this comment

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

API LGTM

Copy link
Member

@jkleinsc jkleinsc left a comment

Choose a reason for hiding this comment

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

API LGTM

Copy link
Member

@jkleinsc jkleinsc left a comment

Choose a reason for hiding this comment

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

LGTM

Copy link
Member

@jkleinsc jkleinsc left a comment

Choose a reason for hiding this comment

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

API LGTM

Copy link
Member

@deepak1556 deepak1556 left a comment

Choose a reason for hiding this comment

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

LGTM

@samuelmaddock samuelmaddock merged commit 26da3c5 into main Jan 31, 2025
61 checks passed
@samuelmaddock samuelmaddock deleted the feat/preload-realm branch January 31, 2025 14:32
Copy link

release-clerk bot commented Jan 31, 2025

Release Notes Persisted

  • Added support for service worker preload scripts.

@trop
Copy link
Contributor

trop bot commented Jan 31, 2025

I was unable to backport this PR to "35-x-y" cleanly;
you will need to perform this backport manually.

@trop trop bot added needs-manual-bp/35-x-y and removed target/35-x-y PR should also be added to the "35-x-y" branch. labels Jan 31, 2025
@erickzhao erickzhao added the needs-docs An API or larger change that needs expanded documentation label Jan 31, 2025
samuelmaddock added a commit that referenced this pull request Jan 31, 2025
…44411)

* feat: preload scripts for service workers

* feat: service worker IPC

* test: service worker preload scripts and ipc
@trop
Copy link
Contributor

trop bot commented Jan 31, 2025

@samuelmaddock has manually backported this PR to "35-x-y", please check out #45408

samuelmaddock added a commit that referenced this pull request Feb 5, 2025
#45408)

feat: service worker preload scripts for improved extensions support (#44411)

* feat: preload scripts for service workers

* feat: service worker IPC

* test: service worker preload scripts and ipc
@trop trop bot added merged/35-x-y PR was merged to the "35-x-y" branch. and removed in-flight/35-x-y labels Feb 5, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
api-review/approved ✅ merged/35-x-y PR was merged to the "35-x-y" branch. needs-docs An API or larger change that needs expanded documentation semver/minor backwards-compatible functionality
Projects
None yet
Development

Successfully merging this pull request may close these issues.

8 participants