Cache plugin package hashes, add a content security policy, and limit browser windows
Plugin runtime cost: - Remove the timed plugin scan. Windows scan at start, on focus, on Refresh, and on plugins-changed. - Keep one package check for each plugin folder. Read and hash the files again only when the entry names, sizes, or modification times change. Enable and load always read all files. An asset read checks the SHA-256 hash of its file. - A changed package still stops and needs a new enable decision. Add tests for the cache, for changes that keep the metadata, and for the enable decision. - Replace the 50 ms wait loops of update and removal with a condition variable. The limit stays at 10 seconds. Command names, arguments, and results do not change. Content security policy: - Set app.security.csp in tauri.conf.json. Keep Tauri from adding nonces to style-src. - Add CSP mode to the smoke tests (pnpm smoke --csp). The dev server sends the same policy with each HTML page, and the harness fails a test on a policy violation. - Decode data URLs without fetch in the background frame test. Capabilities: - Give browser windows their own capability. They load no installed plugin. Add a unit test and a browser window smoke test for the command set. Document the scans, the hash cache, the policy, and the window capabilities.
This commit is contained in:
@@ -18,10 +18,35 @@ export function playwright() {
|
||||
return createRequire(import.meta.url)(process.env.PLAYWRIGHT_MODULE || "playwright");
|
||||
}
|
||||
|
||||
/** Start headless Chromium. CHROME_PATH selects an installed browser. */
|
||||
export function launchBrowser(options = {}) {
|
||||
/** True in CSP mode (`pnpm smoke --csp`). The dev server then sends the app's content security policy. */
|
||||
export const cspMode = process.env.RUNESTONE_CSP === "1";
|
||||
/** The content security policy violations of all pages in CSP mode. `runSmoke` fails when this list is not empty. */
|
||||
export const cspViolations = [];
|
||||
const CSP_PREFIX = "[csp-violation] ";
|
||||
// This function runs in each page and frame. Violations inside workers do not reach it.
|
||||
function reportCspViolations(prefix) {
|
||||
addEventListener("securitypolicyviolation", event => {
|
||||
console.error(prefix + JSON.stringify({ directive: event.effectiveDirective, blocked: event.blockedURI, source: event.sourceFile, line: event.lineNumber, sample: event.sample, page: location.href }));
|
||||
}, true);
|
||||
}
|
||||
/** Record the violations of a browser context or a page. */
|
||||
async function watchCsp(target) {
|
||||
await target.addInitScript(reportCspViolations, CSP_PREFIX);
|
||||
target.on("console", message => {
|
||||
if (message.text().startsWith(CSP_PREFIX)) cspViolations.push(message.text().slice(CSP_PREFIX.length));
|
||||
});
|
||||
}
|
||||
|
||||
/** Start headless Chromium. CHROME_PATH selects an installed browser. In CSP mode, each new context and page records violations. */
|
||||
export async function launchBrowser(options = {}) {
|
||||
const executablePath = process.env.CHROME_PATH;
|
||||
return playwright().chromium.launch({ headless: true, ...(executablePath ? { executablePath } : {}), ...options });
|
||||
const browser = await playwright().chromium.launch({ headless: true, ...(executablePath ? { executablePath } : {}), ...options });
|
||||
if (cspMode) {
|
||||
const { newContext, newPage } = { newContext: browser.newContext.bind(browser), newPage: browser.newPage.bind(browser) };
|
||||
browser.newContext = async (...args) => { const context = await newContext(...args); await watchCsp(context); return context; };
|
||||
browser.newPage = async (...args) => { const page = await newPage(...args); await watchCsp(page); return page; };
|
||||
}
|
||||
return browser;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -267,10 +292,14 @@ export async function runSmoke(name, body, { viewport, timeout, allowPageErrors
|
||||
page = await openPage(browser, { viewport, timeout });
|
||||
await body({ browser, page });
|
||||
if (!allowPageErrors && page.errors.length) throw new Error(`Page errors:\n${page.errors.join("\n")}`);
|
||||
if (cspViolations.length) throw new Error(`Content security policy violations:\n${[...new Set(cspViolations)].join("\n")}`);
|
||||
console.log(`PASS ${name}`);
|
||||
} catch (error) {
|
||||
console.error(`FAIL ${name}`);
|
||||
console.error(error);
|
||||
if (cspViolations.length && !String(error?.message).startsWith("Content security policy violations")) {
|
||||
console.error(`Content security policy violations:\n${[...new Set(cspViolations)].join("\n")}`);
|
||||
}
|
||||
if (page) {
|
||||
if (page.console.length) console.error(`Console:\n${page.console.join("\n")}`);
|
||||
const file = path.join(await outputDir(name), "failure.png");
|
||||
|
||||
@@ -38,7 +38,9 @@ await runSmoke('appearance/backgroundFrames', async ({ browser }) => {
|
||||
};
|
||||
const saved = make('#bd486c', '#438f67');
|
||||
saveAppearance({ theme: 'default', mode: theme, newTabBackground: { image: saved, overlay: 0.15, position: 'center', size: 'cover' } });
|
||||
const urls = await Promise.all([make('#bd486c', '#438f67'), make('#286f9b', '#725ea2')].map(async url => URL.createObjectURL(await (await fetch(url)).blob())));
|
||||
// Decode the data URLs without fetch: the content security policy does not permit `data:` in connect-src.
|
||||
const blob = url => new Blob([Uint8Array.from(atob(url.split(',')[1]), character => character.charCodeAt(0))], { type: 'image/png' });
|
||||
const urls = [make('#bd486c', '#438f67'), make('#286f9b', '#725ea2')].map(url => URL.createObjectURL(blob(url)));
|
||||
window.backgroundTest = { hub: backgroundHub, owner: Symbol(), urls, saved, theme };
|
||||
}, theme);
|
||||
const background = page.locator('.workarea-background');
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
// A browser window (`?browserWindow=true`): it adopts the moved tab, starts no installed plugin,
|
||||
// and calls only the commands that src-tauri/capabilities/browser.json grants.
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import { mockTauri, repoRoot, runSmoke, smokeUrl } from '../_harness/index.mjs';
|
||||
|
||||
await runSmoke('browser/window', async ({ page }) => {
|
||||
await mockTauri(page, {
|
||||
label: 'browser-smoke',
|
||||
commands: test => {
|
||||
const snapshot = { profiles: [{ id: 'user', name: 'User' }], tabs: [{ id: 'moved', profileId: 'user', url: 'https://example.com', title: 'Example', loading: false, blocked: 0, canBack: false, canForward: false, transferToken: 'token' }], bookmarks: [], settings: { search: 'duckduckgo', adblock: true, linkDestination: 'internal', personalRules: '', homepage: '', filterLists: [] } };
|
||||
let next = 0;
|
||||
return {
|
||||
browser_connect: () => 'window-session',
|
||||
browser_stop: () => null,
|
||||
browser_request: ({ session, command, args }) => {
|
||||
if (session !== 'window-session') throw Error('Missing browser session');
|
||||
if (command === 'newTab') { const tabId = 'native-' + (++next); snapshot.tabs.push({ id: tabId, profileId: 'user', url: 'about:blank', title: 'Browser', loading: false, blocked: 0, canBack: false, canForward: false }); return { tabId }; }
|
||||
if (command === 'closeTab') snapshot.tabs = snapshot.tabs.filter(tab => tab.id !== args.tabId);
|
||||
if (command === 'navigate') { const tab = snapshot.tabs.find(tab => tab.id === args.tabId); tab.url = args.input; }
|
||||
return structuredClone(snapshot);
|
||||
},
|
||||
// An installed plugin that a browser window must not load.
|
||||
plugins_snapshot: () => ({ root: 'test', plugins: [{ manifest: { schemaVersion: 1, id: 'org.test.tasks', name: 'Tasks', author: 'Test', description: '', version: '1.0.0', apiVersion: 1, entry: 'main.js', access: 'full-app' }, hash: 'tasks', enabled: true, installedAt: 1, path: '', error: null, removal: false }] }),
|
||||
spelling_menu_install: () => null,
|
||||
spelling_menu_uninstall: () => null,
|
||||
'plugin:window|is_maximized': () => false,
|
||||
};
|
||||
},
|
||||
});
|
||||
await page.goto(smokeUrl + '/?browserWindow=true&browserTab=moved');
|
||||
await page.getByRole('application', { name: 'RuneStone browser' }).waitFor();
|
||||
await page.locator('[data-browser-state="ready"]').waitFor();
|
||||
await page.getByRole('textbox', { name: 'Address or search' }).fill('https://example.org');
|
||||
await page.getByRole('textbox', { name: 'Address or search' }).press('Enter');
|
||||
await page.keyboard.press('Control+t');
|
||||
await page.waitForFunction(() => window.__TEST__.calls.some(call => call.command === 'browser_request' && call.args.command === 'newTab'));
|
||||
|
||||
const capability = JSON.parse(await readFile(path.join(repoRoot, 'src-tauri/capabilities/browser.json'), 'utf8'));
|
||||
const granted = new Set(capability.permissions);
|
||||
const calls = await page.evaluate(() => [...new Set(window.__TEST__.calls.map(call => call.command))]);
|
||||
assert(!calls.includes('plugins_load'), 'A browser window loads no installed plugin.');
|
||||
const missing = calls.filter(command => {
|
||||
const plugin = /^plugin:([^|]+)\|(.+)$/.exec(command);
|
||||
// core:default grants the event plugin and the read-only window commands. Window actions need their own permission.
|
||||
if (plugin) return plugin[1] === 'window' && /^(destroy|close|minimize|toggle_maximize|start_dragging)$/.test(plugin[2])
|
||||
? !granted.has(`core:window:allow-${plugin[2].replaceAll('_', '-')}`) : !['event', 'window', 'webview', 'app'].includes(plugin[1]);
|
||||
return !granted.has(`allow-${command.replaceAll('_', '-')}`);
|
||||
});
|
||||
assert.deepEqual(missing, [], 'Every command of the browser window is in capabilities/browser.json.');
|
||||
console.log(`Browser window commands: ${calls.join(', ')}`);
|
||||
}, { viewport: { width: 1100, height: 750 } });
|
||||
@@ -0,0 +1,24 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
type Capability = { windows: string[]; permissions: string[] };
|
||||
const read = (file: string): string => readFileSync(new URL(`../../../${file}`, import.meta.url), "utf8");
|
||||
const capability = (name: string): Capability => JSON.parse(read(`src-tauri/capabilities/${name}.json`));
|
||||
|
||||
test("browser windows have their own capability, a subset of the main window commands", () => {
|
||||
const browser = capability("browser"), main = capability("default"), settings = capability("settings");
|
||||
assert.deepEqual(browser.windows, ["browser-*"]);
|
||||
for (const other of [main, settings]) assert(!other.windows.some(pattern => pattern.startsWith("browser")), "Only browser.json matches browser windows.");
|
||||
const extra = browser.permissions.filter(permission => !main.permissions.includes(permission));
|
||||
assert.deepEqual(extra, [], "browser.json grants only permissions that default.json also grants.");
|
||||
// Browser windows run no installed plugin, so they need no workspace, file, plugin package, terminal, or Git access.
|
||||
const denied = browser.permissions.filter(permission => /^allow-(workspace|git|pty|backgrounds|tab-transfer|completion|theme|settings-open)-|^allow-plugins-(?!snapshot$)|^(opener|dialog):/.test(permission));
|
||||
assert.deepEqual(denied, []);
|
||||
});
|
||||
|
||||
test("browser windows start only the built-in browser", () => {
|
||||
// The capability split depends on this: a browser window never loads an installed plugin.
|
||||
assert.match(read("src/routes/+page.svelte"), /startExternalPlugins\(browserWindow \? \["runestone\.browser"\] : undefined\)/);
|
||||
assert.match(read("src-tauri/src/browser.rs"), /let label = format!\("browser-\{\}", uuid::Uuid::new_v4\(\)\);/);
|
||||
});
|
||||
Reference in New Issue
Block a user