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
8 changes: 4 additions & 4 deletions packages/snaps-controllers/coverage.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"branches": 93.51,
"functions": 97.36,
"lines": 98.33,
"statements": 98.17
"branches": 93.54,
"functions": 97.38,
"lines": 98.34,
"statements": 98.08
}
1 change: 1 addition & 0 deletions packages/snaps-controllers/src/services/browser.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ describe('browser entrypoint', () => {
'setupMultiplex',
'IframeExecutionService',
'OffscreenExecutionService',
'WebWorkerExecutionService',
'ProxyPostMessageStream',
'WebViewExecutionService',
'WebViewMessageStream',
Expand Down
1 change: 1 addition & 0 deletions packages/snaps-controllers/src/services/browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@ export * from './ProxyPostMessageStream';
export * from './iframe';
export * from './offscreen';
export * from './webview';
export { WebWorkerExecutionService } from './webworker';
1 change: 1 addition & 0 deletions packages/snaps-controllers/src/services/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ export type * from './ExecutionService';
export * from './ProxyPostMessageStream';
export * from './iframe';
export * from './offscreen';
export { WebWorkerExecutionService } from './webworker';
Original file line number Diff line number Diff line change
@@ -0,0 +1,226 @@
import { HandlerType } from '@metamask/snaps-utils';
import {
DEFAULT_SNAP_BUNDLE,
MOCK_LOCAL_SNAP_ID,
MOCK_ORIGIN,
MOCK_SNAP_ID,
spy,
} from '@metamask/snaps-utils/test-utils';
import { describe, it, expect, afterEach } from 'vitest';

import {
WebWorkerExecutionService,
WORKER_POOL_ID,
} from './WebWorkerExecutionService';
import { MOCK_BLOCK_NUMBER } from '../../test-utils/constants';
import { createService } from '../../test-utils/service';

const WORKER_POOL_URL = 'http://localhost:63315/worker/pool/index.html';

describe('WebWorkerExecutionService', () => {
afterEach(() => {
document.getElementById(WORKER_POOL_ID)?.remove();
});

it('can boot', async () => {
const { service } = createService(WebWorkerExecutionService, {
documentUrl: new URL(WORKER_POOL_URL),
});

expect(service).toBeDefined();
await service.terminateAllSnaps();
});

it('only creates a single iframe', async () => {
const { service } = createService(WebWorkerExecutionService, {
documentUrl: new URL(WORKER_POOL_URL),
});

await service.executeSnap({
snapId: MOCK_SNAP_ID,
sourceCode: `
module.exports.onRpcRequest = () => null;
`,
endowments: [],
});

await service.executeSnap({
snapId: MOCK_LOCAL_SNAP_ID,
sourceCode: `
module.exports.onRpcRequest = () => null;
`,
endowments: [],
});

expect(document.getElementById(WORKER_POOL_ID)).not.toBeNull();
expect(document.getElementsByTagName('iframe')).toHaveLength(1);

await service.terminateAllSnaps();
});

it('can create a snap worker and start the snap', async () => {
const { service } = createService(WebWorkerExecutionService, {
documentUrl: new URL(WORKER_POOL_URL),
});

const response = await service.executeSnap({
snapId: 'TestSnap',
sourceCode: `
module.exports.onRpcRequest = () => null;
`,
endowments: [],
});

expect(response).toBe('OK');
await service.terminateAllSnaps();
});

it('executes a snap', async () => {
const { service } = createService(WebWorkerExecutionService, {
documentUrl: new URL(WORKER_POOL_URL),
});

await service.executeSnap({
snapId: MOCK_SNAP_ID,
sourceCode: DEFAULT_SNAP_BUNDLE,
endowments: ['console'],
});

const result = await service.handleRpcRequest(MOCK_SNAP_ID, {
origin: MOCK_ORIGIN,
handler: HandlerType.OnRpcRequest,
request: {
jsonrpc: '2.0',
id: 1,
method: 'foo',
},
});

expect(result).toBe('foo1');

await service.terminateAllSnaps();
});

it('can handle a crashed snap', async () => {
expect.assertions(1);
const { service } = createService(WebWorkerExecutionService, {
documentUrl: new URL(WORKER_POOL_URL),
});

const action = async () => {
await service.executeSnap({
snapId: MOCK_SNAP_ID,
sourceCode: `
throw new Error("Crashed.");
`,
endowments: [],
});
};

await expect(action()).rejects.toThrow(
`Error while running snap '${MOCK_SNAP_ID}': Crashed.`,
);
await service.terminateAllSnaps();
});

it('can detect outbound requests', async () => {
expect.assertions(5);

const { service, messenger } = createService(WebWorkerExecutionService, {
documentUrl: new URL(WORKER_POOL_URL),
});

const publishSpy = spy(messenger, 'publish');

const executeResult = await service.executeSnap({
snapId: MOCK_SNAP_ID,
sourceCode: `
module.exports.onRpcRequest = () => ethereum.request({ method: 'eth_blockNumber', params: [] });
`,
endowments: ['ethereum'],
});

expect(executeResult).toBe('OK');

const result = await service.handleRpcRequest(MOCK_SNAP_ID, {
origin: 'foo',
handler: HandlerType.OnRpcRequest,
request: {
jsonrpc: '2.0',
id: 1,
method: 'foobar',
params: [],
},
});

expect(result).toBe(MOCK_BLOCK_NUMBER);

expect(publishSpy.calls).toHaveLength(2);
expect(publishSpy.calls[0]).toStrictEqual({
args: ['ExecutionService:outboundRequest', MOCK_SNAP_ID],
result: undefined,
});

expect(publishSpy.calls[1]).toStrictEqual({
args: ['ExecutionService:outboundResponse', MOCK_SNAP_ID],
result: undefined,
});

await service.terminateAllSnaps();
publishSpy.reset();
});

it('confirms that events are secured', async () => {
// Check if the security critical properties of the Event object
// are unavailable. This will confirm that executeLockdownEvents works
// inside snaps-execution-environments
const { service } = createService(WebWorkerExecutionService, {
documentUrl: new URL(WORKER_POOL_URL),
});

await service.executeSnap({
snapId: MOCK_SNAP_ID,
sourceCode: `
module.exports.onRpcRequest = async ({ request }) => {
let result;
const promise = new Promise((resolve) => {
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://metamask.io/');
xhr.send();
xhr.onreadystatechange = (ev) => {
result = ev;
resolve();
};
});
await promise;

return {
targetIsUndefined: result.target === undefined,
currentTargetIsUndefined: result.target === undefined,
srcElementIsUndefined: result.target === undefined,
composedPathIsUndefined: result.target === undefined
};
};
`,
endowments: ['console', 'XMLHttpRequest'],
});

const result = await service.handleRpcRequest(MOCK_SNAP_ID, {
origin: 'foo',
handler: HandlerType.OnRpcRequest,
request: {
jsonrpc: '2.0',
id: 1,
method: 'foobar',
params: [],
},
});

expect(result).toStrictEqual({
targetIsUndefined: true,
currentTargetIsUndefined: true,
srcElementIsUndefined: true,
composedPathIsUndefined: true,
});
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
import type { BasePostMessageStream } from '@metamask/post-message-stream';
import { WindowPostMessageStream } from '@metamask/post-message-stream';
import { createWindow } from '@metamask/snaps-utils';
import { assert } from '@metamask/utils';
import { nanoid } from 'nanoid';

import type {
ExecutionServiceArgs,
TerminateJobArgs,
} from '../AbstractExecutionService';
import { AbstractExecutionService } from '../AbstractExecutionService';
import { ProxyPostMessageStream } from '../ProxyPostMessageStream';

type WebWorkerExecutionEnvironmentServiceArgs = {
documentUrl: URL;
} & ExecutionServiceArgs;

export const WORKER_POOL_ID = 'snaps-worker-pool';

export class WebWorkerExecutionService extends AbstractExecutionService<string> {
readonly #documentUrl: URL;

#runtimeStream?: BasePostMessageStream;

/**
* Create a new webworker execution service.
*
* @param args - The constructor arguments.
* @param args.documentUrl - The URL of the worker pool document to use as the
* execution environment.
* @param args.messenger - The messenger to use for communication with the
* `SnapController`.
* @param args.setupSnapProvider - The function to use to set up the snap
* provider.
*/
constructor({
documentUrl,
messenger,
setupSnapProvider,
...args
}: WebWorkerExecutionEnvironmentServiceArgs) {
super({
...args,
messenger,
setupSnapProvider,
});

this.#documentUrl = documentUrl;
}

/**
* Send a termination command to the worker pool document.
*
* @param job - The job to terminate.
*/
// TODO: Either fix this lint violation or explain why it's necessary to
// ignore.
// eslint-disable-next-line @typescript-eslint/no-misused-promises
protected async terminateJob(job: TerminateJobArgs<string>) {
// The `AbstractExecutionService` will have already closed the job stream,
// so we write to the runtime stream directly.
assert(this.#runtimeStream, 'Runtime stream not initialized.');
this.#runtimeStream.write({
jobId: job.id,
data: {
jsonrpc: '2.0',
method: 'terminateJob',
id: nanoid(),
},
});
}

/**
* Create a new stream for the specified job. This wraps the runtime stream
* in a stream specific to the job.
*
* @param jobId - The job ID.
* @returns An object with the worker ID and stream.
*/
protected async initEnvStream(jobId: string) {
// Lazily create the worker pool document.
await this.createDocument();

// `createDocument` should have initialized the runtime stream.
assert(this.#runtimeStream, 'Runtime stream not initialized.');

const stream = new ProxyPostMessageStream({
stream: this.#runtimeStream,
jobId,
});

return { worker: jobId, stream };
}

/**
* Creates the worker pool document to be used as the execution environment.
*
* If the document already exists, this does nothing.
*/
// TODO: Either fix this lint violation or explain why it's necessary to
// ignore.
// eslint-disable-next-line no-restricted-syntax
private async createDocument() {
// We only want to create a single pool.
if (document.getElementById(WORKER_POOL_ID)) {
return;
}

const window = await createWindow({
uri: this.#documentUrl.href,
id: WORKER_POOL_ID,
sandbox: false,
});

this.#runtimeStream = new WindowPostMessageStream({
name: 'parent',
target: 'child',
targetWindow: window,
targetOrigin: '*',
});
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './WebWorkerExecutionService';
Loading
Loading