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: add option to enable cross-origin isolation #234

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
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
4 changes: 3 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/) and this
project adheres to [Semantic Versioning](http://semver.org/).

<!-- ## Unreleased -->
## Unreleased

- Added the `--cross-origin-isolated` CLI flag to enable [cross-origin isolation](https://developer.mozilla.org/en-US/docs/Web/API/Window/crossOriginIsolated).

## [0.7.1] 2024-07-18

Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -872,3 +872,4 @@ tach http://example.com
| `--trace` | `false` | Enable performance tracing ([details](#performance-traces)) |
| `--trace-log-dir` | `${cwd}/logs` | The directory to put tracing log files. Defaults to `${cwd}/logs`. |
| `--trace-cat` | [default categories](./src/defaults.ts) | The tracing categories to record. Should be a string of comma-separated category names |
| `--cross-origin-isolated` | `false` | Add HTTP headers to enable [cross-origin isolation](https://developer.mozilla.org/en-US/docs/Web/API/Window/crossOriginIsolated). |
Copy link
Collaborator

Choose a reason for hiding this comment

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

Nice --cross-origin-isolated option addition! One last thing that I can think of is to add this change to the CHANGELOG under unreleased. Here's another PR as an example: https://github.com/google/tachometer/pull/239/files#diff-06572a96a58dc510037d5efa622f9bec8519bc1beab13c9f251e97e657a9d4edR8-R12

Copy link
Author

Choose a reason for hiding this comment

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

Done!

1 change: 1 addition & 0 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,7 @@ $ tach http://example.com
mountPoints,
resolveBareModules: config.resolveBareModules,
cache: config.mode !== 'manual',
crossOriginIsolated: config.crossOriginIsolated,
});
for (const spec of specs) {
servers.set(spec, server);
Expand Down
6 changes: 6 additions & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ export interface Config {
npmrc?: string;
csvFileStats: string;
csvFileRaw: string;
crossOriginIsolated: boolean;
}

export async function makeConfig(opts: Opts): Promise<Config> {
Expand All @@ -55,6 +56,7 @@ export async function makeConfig(opts: Opts): Promise<Config> {
? parseGithubCheckFlag(opts['github-check'])
: undefined,
remoteAccessibleHost: opts['remote-accessible-host'],
crossOriginIsolated: opts['cross-origin-isolated'],
};

let config: Config;
Expand Down Expand Up @@ -175,6 +177,10 @@ export function applyDefaults(partial: Partial<Config>): Config {
: defaults.resolveBareModules,
root: partial.root !== undefined ? partial.root : defaults.root,
timeout: partial.timeout !== undefined ? partial.timeout : defaults.timeout,
crossOriginIsolated:
partial.crossOriginIsolated !== undefined
? partial.crossOriginIsolated
: defaults.crossOriginIsolated,
};
}

Expand Down
17 changes: 17 additions & 0 deletions src/cross-origin-isolation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/**
* @license
* Copyright 2024 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/
import {Middleware} from 'koa';
AndrewJakubowicz marked this conversation as resolved.
Show resolved Hide resolved

// Enable cross-origin isolation for more precise timers:
// https://developer.chrome.com/blog/cross-origin-isolated-hr-timers/
export function crossOriginIsolation(): Middleware {
// Based on https://github.com/fishel-feng/koa-isolated
return async function isolated(ctx, next) {
ctx.set('Cross-Origin-Opener-Policy', 'same-origin');
ctx.set('Cross-Origin-Embedder-Policy', 'require-corp');
await next();
};
}
1 change: 1 addition & 0 deletions src/defaults.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ export const mode = 'automatic';
export const resolveBareModules = true;
export const forceCleanNpmInstall = false;
export const measurementExpression = 'window.tachometerResult';
export const crossOriginIsolated = false;
export const traceLogDir = path.join(process.cwd(), 'logs');
export const traceCategories = [
'blink',
Expand Down
6 changes: 6 additions & 0 deletions src/flags.ts
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,11 @@ export const optDefs: commandLineUsage.OptionDefinition[] = [
type: String,
defaultValue: defaults.traceCategories.join(','),
},
{
name: 'cross-origin-isolated',
description: 'Add HTTP headers to enable cross-origin isolation',
type: Boolean,
},
];

export interface Opts {
Expand Down Expand Up @@ -266,6 +271,7 @@ export interface Opts {
trace: boolean;
'trace-log-dir': string;
'trace-cat': string;
'cross-origin-isolated': boolean;

// Extra arguments not associated with a flag are put here. These are our
// benchmark names/URLs.
Expand Down
5 changes: 5 additions & 0 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {nodeResolve} from 'koa-node-resolve';

import {BenchmarkResponse, Deferred} from './types.js';
import {NpmInstall} from './versions.js';
import {crossOriginIsolation} from './cross-origin-isolation.js';

import * as url from 'url';
const __dirname = url.fileURLToPath(new URL('.', import.meta.url));
Expand All @@ -31,6 +32,7 @@ export interface ServerOpts {
mountPoints: MountPoint[];
resolveBareModules: boolean;
cache: boolean;
crossOriginIsolated: boolean;
}

export interface MountPoint {
Expand Down Expand Up @@ -91,6 +93,9 @@ export class Server {
this.server = server;
const app = new Koa();

if (opts.crossOriginIsolated) {
app.use(crossOriginIsolation());
}
app.use(bodyParser());
app.use(mount('/submitResults', this.submitResults.bind(this)));
app.use(this.instrumentRequests.bind(this));
Expand Down
5 changes: 5 additions & 0 deletions src/test/config_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ suite('makeConfig', function () {
csvFileStats: '',
csvFileRaw: '',
githubCheck: undefined,
crossOriginIsolated: false,
benchmarks: [
{
browser: {
Expand Down Expand Up @@ -92,6 +93,7 @@ suite('makeConfig', function () {
csvFileRaw: '',
// TODO(aomarks) Be consistent about undefined vs unset.
githubCheck: undefined,
crossOriginIsolated: false,
benchmarks: [
{
browser: {
Expand Down Expand Up @@ -137,6 +139,7 @@ suite('makeConfig', function () {
csvFileStats: '',
csvFileRaw: '',
githubCheck: undefined,
crossOriginIsolated: false,
benchmarks: [
{
browser: {
Expand Down Expand Up @@ -190,6 +193,7 @@ suite('makeConfig', function () {
remoteAccessibleHost: '',
// TODO(aomarks) Be consistent about undefined vs unset.
githubCheck: undefined,
crossOriginIsolated: false,
benchmarks: [
{
browser: {
Expand Down Expand Up @@ -237,6 +241,7 @@ suite('makeConfig', function () {
remoteAccessibleHost: '',
// TODO(aomarks) Be consistent about undefined vs unset.
githubCheck: undefined,
crossOriginIsolated: false,
benchmarks: [
{
browser: {
Expand Down
73 changes: 50 additions & 23 deletions src/test/server_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,20 +17,25 @@ import {testData} from './test_helpers.js';
suite('server', () => {
let server: Server;

const defaultOptions = {
host: 'localhost',
ports: [0], // random
root: testData,
resolveBareModules: true,
npmInstalls: [],
mountPoints: [
{
diskPath: testData,
urlPath: '/',
},
],
cache: true,
crossOriginIsolated: false,
};

setup(async () => {
server = await Server.start({
host: 'localhost',
ports: [0], // random
root: testData,
resolveBareModules: true,
npmInstalls: [],
mountPoints: [
{
diskPath: testData,
urlPath: '/',
},
],
cache: true,
...defaultOptions,
});
});

Expand Down Expand Up @@ -88,18 +93,8 @@ suite('server', () => {
await server.close();

server = await Server.start({
host: 'localhost',
ports: [0], // random
root: testData,
resolveBareModules: true,
...defaultOptions,
npmInstalls: [{installDir, packageJson}],
mountPoints: [
{
diskPath: testData,
urlPath: '/',
},
],
cache: true,
});
});

Expand Down Expand Up @@ -137,4 +132,36 @@ suite('server', () => {
session = server.endSession();
assert.equal(session.bytesSent, 0);
});

test('cross-origin isolation is disabled by default', async () => {
const res = await fetch(`${server.url}/import-bare-module.html`);

assert.equal(res.headers.get('Cross-Origin-Opener-Policy'), null);
assert.equal(res.headers.get('Cross-Origin-Embedder-Policy'), null);
});

suite('cross origin isolation enabled', async () => {
setup(async () => {
// Close the base server and replace it with a custom server that is
// configured with crossOriginIsolated=true
await server.close();
server = await Server.start({
...defaultOptions,
crossOriginIsolated: true,
});
});

test('cross-origin isolation can be enabled', async () => {
const res = await fetch(`${server.url}/import-bare-module.html`);

assert.equal(
res.headers.get('Cross-Origin-Opener-Policy'),
'same-origin'
);
assert.equal(
res.headers.get('Cross-Origin-Embedder-Policy'),
'require-corp'
);
});
});
});
Loading