Skip to content
Draft
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
5 changes: 5 additions & 0 deletions packages/snaps-controllers/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Added

- Add optional `traceContext` to `SnapController:handleRequest` and `ExecutionService:handleRpcRequest`, forwarded to the execution environment
- A malformed trace context is dropped rather than failing the request. Executors that predate this option reject requests carrying it, so only pass it with a matching `@metamask/snaps-execution-environments` version.

## [22.0.1]

### Fixed
Expand Down
2 changes: 1 addition & 1 deletion packages/snaps-controllers/coverage.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"branches": 94.97,
"branches": 95.33,
"functions": 98.78,
"lines": 98.45,
"statements": 98.18
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ import { BasePostMessageStream } from '@metamask/post-message-stream';
import { HandlerType } from '@metamask/snaps-utils';
import { MOCK_SNAP_ID } from '@metamask/snaps-utils/test-utils';
import { Duration, inMilliseconds } from '@metamask/utils';
import type { IncomingHttpHeaders } from 'http';
import { createServer } from 'http';
import type { AddressInfo } from 'net';

import type { ExecutionServiceArgs } from './ExecutionService';
import { NodeThreadExecutionService } from './node';
Expand Down Expand Up @@ -148,4 +151,49 @@ describe('ExecutionService', () => {

expect(await service.terminateSnap(MOCK_SNAP_ID)).toBeUndefined();
});

it('attaches the trace context to fetches made by the Snap', async () => {
const receivedHeaders: IncomingHttpHeaders[] = [];
const server = createServer((request, response) => {
receivedHeaders.push(request.headers);
response.end('OK');
});
await new Promise<void>((resolve) => server.listen(0, resolve));
const { port } = server.address() as AddressInfo;

const { service } = createService(MockExecutionService);
try {
await service.executeSnap({
snapId: MOCK_SNAP_ID,
sourceCode: `
module.exports.onRpcRequest = () =>
fetch('http://localhost:${port}').then((response) => response.text());
`,
endowments: ['fetch'],
});

const traceparent =
'00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01';
const result = await service.handleRpcRequest(MOCK_SNAP_ID, {
origin: 'foo.com',
handler: HandlerType.OnRpcRequest,
request: { jsonrpc: '2.0', id: 1, method: 'foo' },
traceContext: {
traceparent,
baggage: 'a=b',
origins: [`http://localhost:${port}`],
},
});

expect(result).toBe('OK');
expect(receivedHeaders).toHaveLength(1);
expect(receivedHeaders[0]).toStrictEqual(
expect.objectContaining({ traceparent, baggage: 'a=b' }),
);
} finally {
await service.terminateAllSnaps();
server.closeAllConnections();
await new Promise((resolve) => server.close(resolve));
}
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -505,7 +505,7 @@ export abstract class ExecutionService<WorkerType = unknown> {
snapId: string,
options: SnapRpcHookArgs,
): Promise<unknown> {
const { handler, request, origin, originMetadata } = options;
const { handler, request, origin, originMetadata, traceContext } = options;

return await this.#command(snapId, {
id: nanoid(),
Expand All @@ -517,6 +517,8 @@ export abstract class ExecutionService<WorkerType = unknown> {
...(originMetadata && { originMetadata }),
handler,
request: request as JsonRpcRequest,
// Executors reject unknown parameters, so this is only sent when set.
...(traceContext && { traceContext }),
},
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,8 @@ export type SnapControllerInstallSnapsAction = {
* @param options.originMetadata - Optional additional origin metadata for the RPC request.
* @param options.handler - The handler to trigger on the snap for the request.
* @param options.request - The JSON-RPC request object.
* @param options.traceContext - Optional trace context of the client span the
* request belongs to. Dropped if malformed.
* @returns The result of the JSON-RPC request.
*/
export type SnapControllerHandleRequestAction = {
Expand Down
76 changes: 76 additions & 0 deletions packages/snaps-controllers/src/snaps/SnapController.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5505,6 +5505,82 @@ describe('SnapController', () => {
snapController.destroy();
});

it.each([
{
description: 'forwards a valid trace context',
traceContext: {
traceparent:
'00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01',
baggage: 'a=b',
origins: ['https://metamask.io'],
},
forwarded: true,
},
{
description: 'drops a malformed trace context',
traceContext: { traceparent: 'foo', origins: ['https://metamask.io'] },
forwarded: false,
},
{
description: 'drops a trace context with a malformed origin',
traceContext: {
traceparent:
'00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01',
origins: ['metamask.io'],
},
forwarded: false,
},
])('$description', async ({ traceContext, forwarded }) => {
const rootMessenger = getRootMessenger();

const options = getSnapControllerOptions({
rootMessenger,
state: {
snaps: getPersistedSnapsState(),
},
});
const [snapController, service] = await getSnapControllerWithEES(options);

rootMessenger.registerActionHandler(
'PermissionController:hasPermission',
(_origin, permission) => {
return permission === SnapEndowments.Rpc;
},
);

await snapController.handleRequest({
snapId: MOCK_SNAP_ID,
origin: MOCK_ORIGIN,
handler: HandlerType.OnRpcRequest,
request: {
jsonrpc: '2.0',
method: 'bar',
params: {},
id: 1,
},
traceContext,
});

expect(options.messenger.call).toHaveBeenCalledWith(
'ExecutionService:handleRpcRequest',
MOCK_SNAP_ID,
{
origin: MOCK_ORIGIN,
handler: HandlerType.OnRpcRequest,
request: {
id: 1,
method: 'bar',
jsonrpc: '2.0',
params: {},
},
...(forwarded && { traceContext }),
},
);

await service.terminateAllSnaps();
snapController.destroy();
});

it('handlers throw if the request has an invalid "jsonrpc" property', async () => {
const fakeSnap = getPersistedSnapObject({ status: SnapStatus.Running });
const snapId = fakeSnap.id;
Expand Down
7 changes: 7 additions & 0 deletions packages/snaps-controllers/src/snaps/SnapController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,13 +112,15 @@ import {
OnAssetHistoricalPriceResponseStruct,
OnAssetsConversionResponseStruct,
OnAssetsMarketDataResponseStruct,
TraceContextStruct,
} from '@metamask/snaps-utils';
import type {
StorageServiceGetItemAction,
StorageServiceSetItemAction,
StorageServiceRemoveItemAction,
StorageServiceClearAction,
} from '@metamask/storage-service';
import { is } from '@metamask/superstruct';
import type {
Json,
NonEmptyArray,
Expand Down Expand Up @@ -3752,6 +3754,8 @@ export class SnapController extends BaseController<
* @param options.originMetadata - Optional additional origin metadata for the RPC request.
* @param options.handler - The handler to trigger on the snap for the request.
* @param options.request - The JSON-RPC request object.
* @param options.traceContext - Optional trace context of the client span the
* request belongs to. Dropped if malformed.
* @returns The result of the JSON-RPC request.
*/
async handleRequest({
Expand All @@ -3760,6 +3764,7 @@ export class SnapController extends BaseController<
originMetadata,
handler: handlerType,
request: rawRequest,
traceContext,
}: SnapRpcHookArgs & { snapId: SnapId }): Promise<unknown> {
await this.#ensureCanUsePlatform();

Expand Down Expand Up @@ -3893,6 +3898,8 @@ export class SnapController extends BaseController<
originMetadata,
handler: handlerType,
request: transformedRequest,
// A malformed trace context must not fail the request.
...(is(traceContext, TraceContextStruct) && { traceContext }),
},
);

Expand Down
7 changes: 7 additions & 0 deletions packages/snaps-execution-environments/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Added

- Accept an optional `traceContext` in `snapRpc` requests, and attach its `traceparent` and `baggage` headers to the Snap's `fetch` requests to the listed `origins` while that is the Snap's only request in flight
- Requests to any other origin are unchanged, so third-party servers see no new CORS preflight.
- Headers the Snap sets itself are not overwritten.
- Allow `URL` for `@metamask/snaps-utils` in the LavaMoat policies of the iframe, Node.js and WebView executors.

## [11.3.3]

### Removed
Expand Down
2 changes: 1 addition & 1 deletion packages/snaps-execution-environments/coverage.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"branches": 93.03,
"branches": 93.54,
"functions": 96.92,
"lines": 93.54,
"statements": 92.53
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@
"@metamask/snaps-utils": {
"globals": {
"TextEncoder": true,
"URL": true,
"console.error": true,
"console.log": true,
"console.warn": true
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@
"@metamask/snaps-utils": {
"globals": {
"TextEncoder": true,
"URL": true,
"console.error": true,
"console.log": true,
"console.warn": true
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@
"@metamask/snaps-utils": {
"globals": {
"TextEncoder": true,
"URL": true,
"console.error": true,
"console.log": true,
"console.warn": true
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@
"@metamask/snaps-utils": {
"globals": {
"TextEncoder": true,
"URL": true,
"console.error": true,
"console.log": true,
"console.warn": true
Expand Down
Loading
Loading