195 lines
11 KiB
JavaScript
195 lines
11 KiB
JavaScript
// Tests of the extension's background script against a fake browser (docs/BROWSER.md, "Tests"):
|
||
//
|
||
// node tools/extension-test.mjs
|
||
//
|
||
// The background is the extension's one gate to Custos: what it sends to the host must come from the browser's
|
||
// own view of the sender, never from the message; other extensions and odd frames get nothing; a login offered for
|
||
// saving never comes back out of it.
|
||
import assert from 'node:assert/strict';
|
||
import fs from 'node:fs';
|
||
import path from 'node:path';
|
||
import vm from 'node:vm';
|
||
|
||
const root = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
|
||
const code = fs.readFileSync(path.join(root, 'extension', 'background.js'), 'utf8');
|
||
const ID = 'custos-test-id';
|
||
|
||
/** A fresh background with a fake API. `host(req)` answers the native host's requests. */
|
||
function background(host, console = globalThis.console) {
|
||
const sent = [];
|
||
let listener = null;
|
||
const port = {
|
||
onMessage: { addListener: (f) => (port.deliver = f) },
|
||
onDisconnect: { addListener: () => {} },
|
||
postMessage: (m) => {
|
||
sent.push(m);
|
||
queueMicrotask(() => port.deliver({ ...host(m), seq: m.seq }));
|
||
},
|
||
};
|
||
const tabs = [{ id: 1, url: 'https://github.com/login', active: true }];
|
||
const api = {
|
||
runtime: { id: ID, getURL: (p) => `chrome-extension://${ID}/${p}`, connectNative: () => port, onMessage: { addListener: (f) => (listener = f) } },
|
||
tabs: { query: async () => tabs, onRemoved: { addListener: () => {} } },
|
||
action: { setBadgeText: async () => {}, setBadgeBackgroundColor: async () => {} },
|
||
};
|
||
vm.runInNewContext(code, { chrome: api, URL, setTimeout, Promise, queueMicrotask, console });
|
||
const call = (msg, sender) =>
|
||
new Promise((resolve) => {
|
||
// Answers are made in the background's realm: compared as plain JSON.
|
||
const kept = listener(msg, { id: ID, ...sender }, (v) => resolve(JSON.parse(JSON.stringify(v))));
|
||
if (kept !== true) resolve('ignored');
|
||
});
|
||
return { call, sent, tabs };
|
||
}
|
||
|
||
const tab = (url) => ({ id: 1, url });
|
||
const top = (url) => ({ url, frameId: 0, tab: tab(url) });
|
||
const frame = (url, pageUrl) => ({ url, frameId: 7, tab: tab(pageUrl) });
|
||
const tests = [];
|
||
const test = (name, f) => tests.push([name, f]);
|
||
|
||
test('another extension, or a page, is not answered at all', async () => {
|
||
const b = background(() => ({ ok: true, logins: [{ id: 'a' }] }));
|
||
for (const id of ['someone-else', undefined, '']) {
|
||
assert.equal(await b.call({ kind: 'match' }, { ...top('https://github.com/'), id }), 'ignored');
|
||
assert.equal(await b.call({ kind: 'fill', id: 'a' }, { ...top('https://github.com/'), id }), 'ignored');
|
||
}
|
||
assert.equal(b.sent.length, 0);
|
||
});
|
||
|
||
test('the origins come from the browser, never from the message', async () => {
|
||
const b = background(() => ({ ok: true, logins: [] }));
|
||
await b.call({ kind: 'match', origin: 'https://bank.cz', top: 'https://bank.cz' }, top('https://github.com/login?x=1'));
|
||
assert.deepEqual(b.sent.map((m) => [m.op, m.origin, m.top]), [['browser_match', 'https://github.com', 'https://github.com']]);
|
||
});
|
||
|
||
test('a frame asks with its own origin and its page’s', async () => {
|
||
const b = background(() => ({ ok: true, logins: [] }));
|
||
await b.call({ kind: 'match' }, frame('https://evil.net/ad', 'https://github.com/'));
|
||
await b.call({ kind: 'fill', id: 'x' }, frame('https://github.com/login', 'https://evil.net/'));
|
||
assert.deepEqual(
|
||
b.sent.map((m) => [m.op, m.origin, m.top]),
|
||
[
|
||
['browser_match', 'https://evil.net', 'https://github.com'],
|
||
['browser_fill', 'https://github.com', 'https://evil.net'],
|
||
],
|
||
);
|
||
});
|
||
|
||
test('sandboxed, blank, script and file frames get nothing, and nothing is asked', async () => {
|
||
const b = background(() => ({ ok: true, logins: [{ id: 'a' }] }));
|
||
const odd = [
|
||
{ ...frame('https://github.com/login', 'https://evil.net/'), origin: 'null' },
|
||
{ ...top('https://github.com/'), origin: 'https://evil.net' },
|
||
frame('about:blank', 'https://github.com/'),
|
||
top('javascript:alert(1)'),
|
||
top('file:///C:/x.html'),
|
||
top('data:text/html,<input type=password>'),
|
||
{ url: 'https://github.com/', frameId: 3 },
|
||
];
|
||
for (const s of odd) {
|
||
assert.deepEqual(await b.call({ kind: 'match' }, s), { ok: false, error: 'no_match' }, JSON.stringify(s));
|
||
assert.deepEqual(await b.call({ kind: 'fill', id: 'a' }, s), { ok: false, error: 'no_match' });
|
||
}
|
||
assert.equal(b.sent.length, 0);
|
||
});
|
||
|
||
test('a locked Custos answers nothing but locked', async () => {
|
||
const b = background(() => ({ ok: false, error: 'locked' }));
|
||
const r = await b.call({ kind: 'fill', id: 'a' }, top('https://github.com/'));
|
||
assert.deepEqual(r, { ok: false, error: 'locked', seq: 1 });
|
||
});
|
||
|
||
test('a login offered for saving never comes back out, and goes only to Custos', async () => {
|
||
const b = background((m) => (m.op === 'browser_save' ? { ok: true, saved: 'new' } : { ok: true, code: '123456' }));
|
||
const at = top('https://github.com/login');
|
||
const offered = await b.call({ kind: 'offer-save', username: 'mark', password: 'hunter2-secret' }, at);
|
||
assert.deepEqual(offered, { ok: true, offer: { host: 'github.com', username: 'mark', update: false } });
|
||
// Another page of the site in the same tab sees the offer, without the password; a frame or another site does not.
|
||
assert.deepEqual(await b.call({ kind: 'pending-save' }, top('https://github.com/home')), { ok: true, offer: { host: 'github.com', username: 'mark', update: false } });
|
||
assert.deepEqual(await b.call({ kind: 'pending-save' }, frame('https://github.com/x', 'https://github.com/')), { ok: true, offer: null });
|
||
assert.deepEqual(await b.call({ kind: 'pending-save' }, top('https://evil.net/')), { ok: true, offer: null });
|
||
const popup = await b.call({ kind: 'match-tab' }, { url: `chrome-extension://${ID}/popup.html` });
|
||
assert.ok(!JSON.stringify(popup).includes('hunter2'), 'the popup never sees the password');
|
||
// A frame cannot save; the top page can, once.
|
||
assert.deepEqual(await b.call({ kind: 'save' }, frame('https://github.com/x', 'https://github.com/')), { ok: false, error: 'bad_request' });
|
||
const saved = await b.call({ kind: 'save' }, top('https://github.com/home'));
|
||
assert.equal(saved.saved, 'new');
|
||
const req = b.sent.find((m) => m.op === 'browser_save');
|
||
assert.deepEqual([req.origin, req.top, req.username, req.password], ['https://github.com', 'https://github.com', 'mark', 'hunter2-secret']);
|
||
assert.deepEqual(await b.call({ kind: 'save' }, top('https://github.com/home')), { ok: false, error: 'gone' });
|
||
});
|
||
|
||
test('an offer needs a password, from a web page', async () => {
|
||
const b = background(() => ({ ok: true }));
|
||
assert.equal((await b.call({ kind: 'offer-save', username: 'm', password: '' }, top('https://github.com/'))).ok, false);
|
||
assert.equal((await b.call({ kind: 'offer-save', username: 'm', password: 'p' }, top('about:blank'))).ok, false);
|
||
assert.equal((await b.call({ kind: 'offer-save', username: 'm', password: 'x'.repeat(4097) }, top('https://a.cz/'))).ok, false);
|
||
});
|
||
|
||
test('a new password is asked for by origin only, and goes back only to the frame that asked', async () => {
|
||
const b = background((m) => (m.op === 'browser_generate' ? { ok: true, password: 'Gen-3rated!pw', bits: 128 } : { ok: true }));
|
||
const r = await b.call({ kind: 'generate', length: 4, origin: 'https://bank.cz' }, frame('https://accounts.example/signup', 'https://example.com/'));
|
||
assert.deepEqual(r, { ok: true, password: 'Gen-3rated!pw', bits: 128, seq: 1 });
|
||
assert.deepEqual(b.sent.map((m) => [m.op, m.origin, m.top, m.length]), [['browser_generate', 'https://accounts.example', 'https://example.com', undefined]]);
|
||
for (const s of [{ ...top('https://a.cz/'), origin: 'null' }, top('about:blank'), top('file:///x.html')]) {
|
||
assert.deepEqual(await b.call({ kind: 'generate' }, s), { ok: false, error: 'no_match' });
|
||
}
|
||
assert.equal(b.sent.length, 1);
|
||
});
|
||
|
||
test('the popup’s requests come only from the extension’s own pages, never from a content script', async () => {
|
||
const b = background((m) => (m.op === 'browser_generate' ? { ok: true, password: 'Gen-3rated!pw', bits: 128 } : { ok: true, totp: '123456', logins: [] }));
|
||
const popup = { url: `chrome-extension://${ID}/popup.html` };
|
||
for (const kind of ['match-tab', 'totp-tab', 'generate-tab', 'save-tab', 'dismiss-tab']) {
|
||
assert.deepEqual(await b.call({ kind, id: 'a' }, frame('https://evil.net/ad', 'https://github.com/')), { ok: false, error: 'bad_request' }, kind);
|
||
assert.deepEqual(await b.call({ kind, id: 'a' }, top('https://github.com/')), { ok: false, error: 'bad_request' }, kind);
|
||
}
|
||
assert.equal(b.sent.length, 0);
|
||
const g = await b.call({ kind: 'generate-tab' }, popup);
|
||
assert.deepEqual([g.password, g.origin], ['Gen-3rated!pw', 'https://github.com']);
|
||
assert.deepEqual(b.sent.map((m) => [m.op, m.origin, m.top]), [['browser_generate', 'https://github.com', 'https://github.com']]);
|
||
});
|
||
|
||
test('an offer says Update when Custos has that login, and a change-password form finds its one login', async () => {
|
||
const logins = [{ id: 'a', title: 'GitHub', username: 'mark', totp: false }];
|
||
const b = background((m) => (m.op === 'browser_match' ? { ok: true, logins } : { ok: true, saved: 'updated' }));
|
||
const at = top('https://github.com/settings/password');
|
||
assert.deepEqual(await b.call({ kind: 'offer-save', username: 'mark', password: 'new-pw-1' }, at), { ok: true, offer: { host: 'github.com', username: 'mark', update: true } });
|
||
// No username on the form, and one login for the site: that login is the one that changes.
|
||
assert.deepEqual(await b.call({ kind: 'offer-save', username: '', password: 'new-pw-2' }, at), { ok: true, offer: { host: 'github.com', username: 'mark', update: true } });
|
||
assert.deepEqual(await b.call({ kind: 'offer-save', username: 'petra', password: 'new-pw-3' }, at), { ok: true, offer: { host: 'github.com', username: 'petra', update: false } });
|
||
// A locked Custos cannot say: it is offered as new, and Custos's card decides.
|
||
const locked = background((m) => (m.op === 'browser_match' ? { ok: false, error: 'locked' } : { ok: true }));
|
||
assert.deepEqual(await locked.call({ kind: 'offer-save', username: '', password: 'p' }, at), { ok: true, offer: { host: 'github.com', username: '', update: false } });
|
||
});
|
||
|
||
test('nothing is ever written to the console, and no script of the extension can', async () => {
|
||
const said = [];
|
||
const quiet = new Proxy({}, { get: () => (...a) => said.push(a) });
|
||
const b = background((m) => (m.op === 'browser_generate' ? { ok: true, password: 'Gen-3rated!pw' } : { ok: true, logins: [], saved: 'new' }), quiet);
|
||
const at = top('https://github.com/login');
|
||
await b.call({ kind: 'offer-save', username: 'mark', password: 'hunter2-secret' }, at);
|
||
await b.call({ kind: 'save' }, at);
|
||
await b.call({ kind: 'generate' }, at);
|
||
await b.call({ kind: 'fill', id: 'a' }, at);
|
||
await b.call({ kind: 'nonsense' }, at);
|
||
assert.deepEqual(said, []);
|
||
for (const f of fs.readdirSync(path.join(root, 'extension')).filter((f) => f.endsWith('.js'))) {
|
||
assert.ok(!/\bconsole\s*\.|\bdebugger\b/.test(fs.readFileSync(path.join(root, 'extension', f), 'utf8')), f);
|
||
}
|
||
});
|
||
|
||
let failed = 0;
|
||
for (const [name, f] of tests) {
|
||
try {
|
||
await f();
|
||
console.log(`ok ${name}`);
|
||
} catch (e) {
|
||
failed++;
|
||
console.log(`FAIL ${name}\n${e.stack}`);
|
||
}
|
||
}
|
||
console.log(`${tests.length - failed} passed, ${failed} failed`);
|
||
process.exit(failed ? 1 : 0);
|