Files
client/test/bookmark-secrets.test.js
T

366 lines
22 KiB
JavaScript

'use strict';
const test = require('node:test');
const assert = require('node:assert/strict');
const crypto = require('node:crypto');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { Prefs } = require('../app/main/prefs');
const { registerBookmarkIpc } = require('../app/main/bookmark-secrets');
const bookmarks = require('../app/renderer/shared/bookmarks.js');
const IDENTITY = `${'A'.repeat(27)}=`;
const SECRET = 'Hunter2-server-secret';
const CHANNEL_SECRET = 'channel-door-secret';
/** OS-backed storage stand-in with real authenticated encryption; `prefix` mirrors Chromium's version tag. */
function fakeStorage({ backend = 'gnome_libsecret', available = true, prefix = 'v11', key = crypto.randomBytes(32) } = {}) {
const storage = {
key, backend, available, prefix, calls: [],
isEncryptionAvailable() { storage.calls.push('available'); return storage.available; },
getSelectedStorageBackend: () => storage.backend,
setUsePlainTextEncryption() { storage.calls.push('plaintext'); },
encryptString(plain) {
storage.calls.push('encrypt');
storage.onEncrypt?.();
const iv = crypto.randomBytes(12);
const cipher = crypto.createCipheriv('aes-256-gcm', storage.key, iv);
const body = Buffer.concat([cipher.update(plain, 'utf8'), cipher.final()]);
return Buffer.concat([Buffer.from(storage.prefix, 'latin1'), iv, body, cipher.getAuthTag()]);
},
decryptString(sealed) {
storage.calls.push('decrypt');
storage.onDecrypt?.();
const iv = sealed.subarray(3, 15);
const decipher = crypto.createDecipheriv('aes-256-gcm', storage.key, iv);
decipher.setAuthTag(sealed.subarray(sealed.length - 16));
return Buffer.concat([decipher.update(sealed.subarray(15, sealed.length - 16)), decipher.final()]).toString('utf8');
},
};
return storage;
}
function fixture(t, { platform = 'win32', storage = fakeStorage(), testOffscreen = false, dir = null, servers } = {}) {
if (!dir) {
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'teamspeach-bookmark-secrets-'));
t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
}
const file = path.join(dir, 'prefs.json');
const prefs = new Prefs(file);
if (servers) prefs.set({ savedServers: servers });
const handlers = new Map();
const calls = [];
const connection = { state: 'disconnected', session: 0, core: {} };
const connections = new Map([['c1', connection]]);
const f = {
dir, file, prefs, storage, calls, connection, connections, trusted: true,
onRequest: async () => ({ ok: true, result: {} }),
};
f.service = registerBookmarkIpc({
ipcMain: { handle: (name, fn) => handlers.set(name, fn) },
trustedSender: () => f.trusted,
prefs, safeStorage: storage, platform, testOffscreen,
getConnection: (id) => connections.get(id) ?? null,
request: (id, cmd, args) => { calls.push([id, cmd, args]); return f.onRequest(id, cmd, args); },
});
f.invoke = (name, ...args) => handlers.get(`bookmarks:${name}`)({ sender: {} }, ...args);
// The parent's generic prefs:set path: protector and write with no await between.
f.genericWrite = (partial) => prefs.set(f.service.protectPrefsPatch(partial));
f.server = (id) => prefs.get().savedServers.find((server) => server.id === id);
return f;
}
const home = (extra = {}) => ({ id: 'bookmarka', name: 'Home', address: 'voice.example.org', ...extra });
const other = (extra = {}) => ({ id: 'bookmarkb', name: 'Other', address: 'attacker.example.net', ...extra });
test('saved passwords persist only as OS ciphertext and survive a restart', async (t) => {
const storage = fakeStorage();
const f = fixture(t, { storage, servers: [home()] });
const saved = await f.invoke('password-set', 'bookmarka', ' voice.example.org ', 'server', SECRET);
assert.equal(saved.ok, true);
assert.ok(bookmarks.validSecret(saved.prefs.savedServers[0].server_password_encrypted));
assert.ok(!JSON.stringify(saved).includes(SECRET));
assert.ok(!fs.readFileSync(f.file, 'utf8').includes(SECRET));
assert.deepEqual(await f.invoke('password-state', 'bookmarka'), { ok: true, available: true, serverPasswordSaved: true, channelPasswordSaved: false });
assert.ok(!storage.calls.includes('plaintext'));
const restarted = fixture(t, { storage, dir: f.dir });
assert.deepEqual(await restarted.invoke('password-reveal', 'bookmarka', 'voice.example.org', 'server'), { ok: true, value: SECRET });
const cleared = await restarted.invoke('password-set', 'bookmarka', 'voice.example.org', 'server', '');
assert.equal(cleared.ok, true);
assert.equal(restarted.server('bookmarka').server_password_encrypted, undefined);
});
test('Linux basic_text, unknown backends and hardcoded-key ciphertext are refused without plaintext fallback', async (t) => {
for (const [backend, reason] of [['basic_text', 'insecure_backend'], ['unknown', 'unknown_backend']]) {
const storage = fakeStorage({ backend });
const f = fixture(t, { platform: 'linux', storage, servers: [home()] });
const state = await f.invoke('password-state', 'bookmarka');
assert.deepEqual(state, { ok: true, available: false, serverPasswordSaved: false, channelPasswordSaved: false, reason });
const set = await f.invoke('password-set', 'bookmarka', 'voice.example.org', 'server', SECRET);
assert.equal(set.error.code, 'storage_unavailable');
assert.ok(!storage.calls.includes('encrypt') && !storage.calls.includes('plaintext'));
assert.equal(f.server('bookmarka').server_password_encrypted, undefined);
}
// A keyring backend that still produced Chromium's hardcoded-key format is not stored.
const weak = fakeStorage({ prefix: 'v10' });
const f = fixture(t, { platform: 'linux', storage: weak, servers: [home()] });
assert.equal((await f.invoke('password-set', 'bookmarka', 'voice.example.org', 'server', SECRET)).error.code, 'encryption_failed');
assert.equal(f.server('bookmarka').server_password_encrypted, undefined);
// Ciphertext saved under a keyring cannot be used once the run falls back to basic_text.
const storage = fakeStorage();
const saved = fixture(t, { platform: 'linux', storage, servers: [home({ auto_connect: true })] });
await saved.invoke('password-set', 'bookmarka', 'voice.example.org', 'server', SECRET);
storage.backend = 'basic_text';
assert.equal((await saved.invoke('password-reveal', 'bookmarka', 'voice.example.org', 'server')).error.code, 'storage_unavailable');
assert.equal((await saved.invoke('connect', 'c1', 'bookmarka')).error.code, 'storage_unavailable');
assert.deepEqual(saved.calls, []);
});
test('status checks never open the macOS Keychain and hidden runs refuse non-DPAPI storage', async (t) => {
const keychain = fakeStorage();
const mac = fixture(t, { platform: 'darwin', storage: keychain, servers: [home()] });
assert.equal((await mac.invoke('password-state', 'bookmarka')).available, true);
assert.deepEqual(keychain.calls, []);
const hidden = fixture(t, { platform: 'darwin', storage: fakeStorage(), testOffscreen: true, servers: [home()] });
assert.equal((await hidden.invoke('password-state', 'bookmarka')).reason, 'test_mode');
assert.equal((await hidden.invoke('password-set', 'bookmarka', 'voice.example.org', 'server', SECRET)).error.code, 'storage_unavailable');
});
test('ciphertext moved to another address or field never reaches a connect', async (t) => {
const f = fixture(t, { servers: [home(), other()] });
await f.invoke('password-set', 'bookmarka', 'voice.example.org', 'server', SECRET);
const sealed = f.server('bookmarka').server_password_encrypted;
// Tampering below the protector (for example an edited prefs file).
f.prefs.set({ savedServers: [home({ server_password_encrypted: sealed }), other({ server_password_encrypted: sealed })] });
const moved = await f.invoke('connect', 'c1', 'bookmarkb');
assert.equal(moved.error.code, 'password_mismatch');
f.prefs.set({ savedServers: [home({ channel_password_encrypted: sealed }), other()] });
assert.equal((await f.invoke('connect', 'c1', 'bookmarka')).error.code, 'password_mismatch');
assert.equal((await f.invoke('password-reveal', 'bookmarka', 'voice.example.org', 'channel')).error.code, 'password_mismatch');
assert.deepEqual(f.calls, []);
});
test('corrupted ciphertext fails the connect instead of sending an empty password', async (t) => {
const f = fixture(t, { servers: [home()] });
await f.invoke('password-set', 'bookmarka', 'voice.example.org', 'server', SECRET);
const sealed = Buffer.from(f.server('bookmarka').server_password_encrypted, 'base64');
sealed[sealed.length - 20] ^= 1;
f.prefs.set({ savedServers: [home({ server_password_encrypted: sealed.toString('base64') })] });
const result = await f.invoke('connect', 'c1', 'bookmarka');
assert.equal(result.error.code, 'password_unreadable');
assert.ok(!JSON.stringify(result).includes(SECRET));
assert.deepEqual(f.calls, []);
});
test('stale generic writes cannot drop, replace or resurrect ciphertext; an address change clears it', async (t) => {
const f = fixture(t, { servers: [home(), other()] });
const stale = f.prefs.get().savedServers;
await f.invoke('password-set', 'bookmarka', 'voice.example.org', 'server', SECRET);
const current = f.server('bookmarka').server_password_encrypted;
// Renderer copy from before the save: renaming keeps the new ciphertext.
f.genericWrite({ savedServers: stale.map((s) => (s.id === 'bookmarka' ? { ...s, name: 'Renamed' } : s)) });
assert.equal(f.server('bookmarka').name, 'Renamed');
assert.equal(f.server('bookmarka').server_password_encrypted, current);
// Forged replacement on an existing bookmark is ignored.
f.genericWrite({ savedServers: f.prefs.get().savedServers.map((s) => ({ ...s, server_password_encrypted: 'AAAA' })) });
assert.equal(f.server('bookmarka').server_password_encrypted, current);
assert.equal(f.server('bookmarkb').server_password_encrypted, undefined);
// A cleared password is not restored by a copy that still carries it.
const carrying = f.prefs.get().savedServers;
await f.invoke('password-set', 'bookmarka', 'voice.example.org', 'server', '');
f.genericWrite({ savedServers: carrying });
assert.equal(f.server('bookmarka').server_password_encrypted, undefined);
await f.invoke('password-set', 'bookmarka', 'voice.example.org', 'server', SECRET);
f.genericWrite({ savedServers: f.prefs.get().savedServers.map((s) => (s.id === 'bookmarka' ? { ...s, address: 'elsewhere.example.org' } : s)) });
assert.equal(f.server('bookmarka').server_password_encrypted, undefined);
// Going back to the old address does not bring the old ciphertext back either.
f.genericWrite({ savedServers: f.prefs.get().savedServers.map((s) => (s.id === 'bookmarka' ? { ...s, address: 'voice.example.org', server_password_encrypted: current } : s)) });
assert.equal(f.server('bookmarka').server_password_encrypted, undefined);
});
test('explicit duplication keeps the identical ciphertext; forged or re-addressed copies are rejected', async (t) => {
const f = fixture(t, { servers: [home(), other()] });
await f.invoke('password-set', 'bookmarka', 'voice.example.org', 'server', SECRET);
const sealed = f.server('bookmarka').server_password_encrypted;
const copy = bookmarks.duplicate(f.prefs.get(), 'bookmarka', 'bookmarkc');
f.genericWrite({ savedServers: copy.savedServers, bookmarkOrder: copy.bookmarkOrder });
assert.equal(f.server('bookmarkc').server_password_encrypted, sealed);
assert.equal((await f.invoke('connect', 'c1', 'bookmarkc')).ok, true);
assert.equal(f.calls.at(-1)[2].server_password, SECRET);
const add = (entry) => () => f.genericWrite({ savedServers: [...f.prefs.get().savedServers, entry] });
assert.throws(add({ id: 'bookmarkd', name: 'Forged', address: 'voice.example.org', server_password_encrypted: 'AAAA' }), /server_password_encrypted/);
assert.throws(add({ id: 'bookmarkd', name: 'Moved', address: 'attacker.example.net', server_password_encrypted: sealed }), /server_password_encrypted/);
assert.throws(add({ id: 'bookmarkd', name: 'Swapped', address: 'voice.example.org', channel_password_encrypted: sealed }), /channel_password_encrypted/);
assert.equal(f.server('bookmarkd'), undefined);
// Deleting a bookmark removes its ciphertext in the same write.
f.genericWrite({ savedServers: f.prefs.get().savedServers.filter((s) => s.id !== 'bookmarka') });
assert.equal(f.server('bookmarka'), undefined);
assert.ok(!fs.readFileSync(f.file, 'utf8').includes(`"id": "bookmarka"`));
});
test('password saves recompute from fresh prefs after encryption and stay bound to the current address', async (t) => {
const storage = fakeStorage();
const f = fixture(t, { storage, servers: [home(), other()] });
// Metadata changed while the OS encrypted: the rename survives the password write.
storage.onEncrypt = () => f.genericWrite({ savedServers: f.prefs.get().savedServers.map((s) => (s.id === 'bookmarka' ? { ...s, name: 'Meanwhile' } : s)) });
assert.equal((await f.invoke('password-set', 'bookmarka', 'voice.example.org', 'server', SECRET)).ok, true);
assert.equal(f.server('bookmarka').name, 'Meanwhile');
assert.ok(f.server('bookmarka').server_password_encrypted);
// The address changed while encrypting: nothing is stored for the new target.
storage.onEncrypt = () => f.genericWrite({ savedServers: f.prefs.get().savedServers.map((s) => (s.id === 'bookmarkb' ? { ...s, address: 'moved.example.net' } : s)) });
assert.equal((await f.invoke('password-set', 'bookmarkb', 'attacker.example.net', 'channel', CHANNEL_SECRET)).error.code, 'address_changed');
assert.equal(f.server('bookmarkb').channel_password_encrypted, undefined);
storage.onEncrypt = null;
assert.equal((await f.invoke('password-set', 'bookmarka', 'stale.example.org', 'server', SECRET)).error.code, 'address_changed');
assert.equal((await f.invoke('password-reveal', 'bookmarka', 'stale.example.org', 'server')).error.code, 'address_changed');
assert.equal((await f.invoke('password-set', 'bookmarka', 'voice.example.org', 'server', 'x'.repeat(256))).error.code, 'bad_request');
assert.equal((await f.invoke('password-set', 'bookmarka', 'voice.example.org', 'server', 'line\nbreak')).error.code, 'bad_request');
assert.equal((await f.invoke('password-set', 'bookmarka', 'voice.example.org', 'identity', SECRET)).error.code, 'bad_request');
assert.equal((await f.invoke('password-set', 'bookmarka', 'voice.example.org', ['server'], SECRET)).error.code, 'bad_request');
f.trusted = false;
for (const [name, args] of [['password-reveal', ['bookmarka', 'voice.example.org', 'server']], ['password-set', ['bookmarka', 'voice.example.org', 'server', '']], ['connect', ['c1', 'bookmarka']]]) {
assert.equal((await f.invoke(name, ...args)).error.code, 'forbidden');
}
assert.ok(f.server('bookmarka').server_password_encrypted);
assert.deepEqual(f.calls, []);
});
test('connect resolves the stored target in main and dispatches validated arguments', async (t) => {
const f = fixture(t, { servers: [home({ identity_id: IDENTITY, nickname: 'Override', channel: 'Lobby/Sub' })] });
await f.invoke('password-set', 'bookmarka', 'voice.example.org', 'server', SECRET);
await f.invoke('password-set', 'bookmarka', 'voice.example.org', 'channel', CHANNEL_SECRET);
const result = await f.invoke('connect', 'c1', 'bookmarka');
assert.deepEqual(result, { ok: true, result: {} });
assert.deepEqual(f.calls, [['c1', 'connect', { address: 'voice.example.org', identity_id: IDENTITY, nickname: 'Override', channel: 'Lobby/Sub', server_password: SECRET, channel_password: CHANNEL_SECRET }]]);
f.connection.state = 'connected';
assert.equal((await f.invoke('connect', 'c1', 'bookmarka')).error.code, 'already_connected');
assert.equal((await f.invoke('connect', 'c9', 'bookmarka')).error.code, 'connection_closed');
assert.equal((await f.invoke('connect', 'c1', 'bookmarka', 'yes')).error.code, 'bad_request');
assert.equal(f.calls.length, 1);
});
test('startup mute is input-only, startup-only, applied before connect and never unmutes', async (t) => {
const f = fixture(t, { servers: [home({ auto_connect: true, auto_connect_muted: true }), other({ auto_connect: true })] });
assert.equal((await f.invoke('connect', 'c1', 'bookmarka', true)).ok, true);
assert.deepEqual(f.calls.map(([, cmd, args]) => [cmd, args]), [['set_audio', { input_muted: true }], ['connect', { address: 'voice.example.org' }]]);
f.calls.length = 0;
await f.invoke('connect', 'c1', 'bookmarka', false);
await f.invoke('connect', 'c1', 'bookmarkb', true);
assert.deepEqual(f.calls.map(([, cmd]) => cmd), ['connect', 'connect']);
// A failed mute does not connect unmuted.
f.calls.length = 0;
f.onRequest = async (_id, cmd) => (cmd === 'set_audio' ? { ok: false, error: { code: 'core_unavailable', message: 'The core is not running' } } : { ok: true, result: {} });
assert.equal((await f.invoke('connect', 'c1', 'bookmarka', true)).error.code, 'core_unavailable');
assert.deepEqual(f.calls.map(([, cmd]) => cmd), ['set_audio']);
});
test('credentials are never sent after the connection, window or bookmark changed during the mute', async (t) => {
const changes = [
['session ended', 'connection_changed', (f) => { f.connection.session += 1; }],
['tab replaced', 'connection_changed', (f) => { f.connections.set('c1', { ...f.connection }); }],
['core restarted', 'connection_changed', (f) => { f.connection.core = {}; }],
['window changed', 'forbidden', (f) => { f.trusted = false; }],
['address edited', 'bookmark_changed', (f) => f.genericWrite({ savedServers: f.prefs.get().savedServers.map((s) => ({ ...s, address: 'attacker.example.net' })) })],
['auto-connect disabled', 'not_startup', (f) => f.genericWrite({ savedServers: f.prefs.get().savedServers.map(({ auto_connect: _off, ...s }) => s) })],
];
for (const [label, code, change] of changes) {
const f = fixture(t, { servers: [home({ auto_connect: true, auto_connect_muted: true })] });
await f.invoke('password-set', 'bookmarka', 'voice.example.org', 'server', SECRET);
f.onRequest = async (_id, cmd) => { if (cmd === 'set_audio') change(f); return { ok: true, result: {} }; };
const result = await f.invoke('connect', 'c1', 'bookmarka', true);
assert.equal(result.error?.code, code, label);
assert.deepEqual(f.calls.map(([, cmd]) => cmd), ['set_audio'], label);
assert.ok(!JSON.stringify(result).includes(SECRET));
}
});
test('hidden test runs never dispatch a bookmark connect and list no startup bookmarks', async (t) => {
const f = fixture(t, { testOffscreen: true, servers: [home({ auto_connect: true, auto_connect_muted: true })] });
assert.deepEqual(await f.invoke('startup'), { ok: true, bookmarks: [] });
assert.equal((await f.invoke('connect', 'c1', 'bookmarka', true)).error.code, 'test_safety');
assert.deepEqual(f.calls, []);
});
test('startup lists only auto-connect bookmarks in display order without secrets', async (t) => {
const f = fixture(t, { servers: [home({ auto_connect: true, nickname: 'Override' }), other(), { id: 'bookmarkc', name: 'Third', address: 'third.example.org', identity_id: IDENTITY, channel: 'cid:7', auto_connect: true }] });
f.genericWrite({ bookmarkOrder: ['bookmarkc', 'bookmarkb', 'bookmarka'] });
await f.invoke('password-set', 'bookmarka', 'voice.example.org', 'server', SECRET);
assert.deepEqual(await f.invoke('startup'), { ok: true, bookmarks: [
{ id: 'bookmarkc', address: 'third.example.org', identity_id: IDENTITY, channel: 'cid:7' },
{ id: 'bookmarka', address: 'voice.example.org', nickname: 'Override' },
] });
});
test('a delayed encryption cannot restore a password cleared during the OS interaction', async (t) => {
const f = fixture(t, { servers: [home()] });
await f.invoke('password-set', 'bookmarka', 'voice.example.org', 'server', SECRET);
f.storage.onEncrypt = () => {
const next = { ...f.server('bookmarka') };
delete next.server_password_encrypted;
f.prefs.set({ savedServers: [next] });
};
const result = await f.invoke('password-set', 'bookmarka', 'voice.example.org', 'server', 'older pending edit');
assert.equal(result.error.code, 'password_changed');
assert.equal(f.server('bookmarka').server_password_encrypted, undefined);
});
test('reveal does not return plaintext after the window or credential changes during decryption', async (t) => {
for (const change of ['window', 'password']) {
const f = fixture(t, { servers: [home()] });
await f.invoke('password-set', 'bookmarka', 'voice.example.org', 'server', SECRET);
f.storage.onDecrypt = () => {
if (change === 'window') f.trusted = false;
else f.prefs.set({ savedServers: [home()] });
};
const result = await f.invoke('password-reveal', 'bookmarka', 'voice.example.org', 'server');
assert.equal(result.error.code, change === 'window' ? 'forbidden' : 'password_changed');
assert.equal(Object.hasOwn(result, 'value'), false);
}
});
test('decryption cannot outlive a connection, bookmark or window grant and then connect', async (t) => {
for (const change of ['window', 'session', 'address']) {
const f = fixture(t, { servers: [home()] });
await f.invoke('password-set', 'bookmarka', 'voice.example.org', 'server', SECRET);
f.storage.onDecrypt = () => {
if (change === 'window') f.trusted = false;
else if (change === 'session') f.connection.session += 1;
else f.genericWrite({ savedServers: [home({ address: 'changed.example.org' })] });
};
const result = await f.invoke('connect', 'c1', 'bookmarka', false);
assert.equal(result.error.code, { window: 'forbidden', session: 'connection_changed', address: 'bookmark_changed' }[change]);
assert.deepEqual(f.calls, []);
}
});
test('renderer reload cannot enumerate startup connections a second time', async (t) => {
const f = fixture(t, { servers: [home({ auto_connect: true })] });
assert.deepEqual((await f.invoke('startup')).bookmarks.map(bookmark => bookmark.id), ['bookmarka']);
assert.deepEqual(await f.invoke('startup'), { ok: true, bookmarks: [] });
});
test('a saved password can be forgotten after secure storage becomes unavailable', async (t) => {
const f = fixture(t, { platform: 'linux', servers: [home()] });
await f.invoke('password-set', 'bookmarka', 'voice.example.org', 'server', SECRET);
f.storage.backend = 'basic_text';
f.storage.available = false;
const result = await f.invoke('password-set', 'bookmarka', 'voice.example.org', 'server', '');
assert.equal(result.ok, true);
assert.equal(result.prefs.savedServers[0].server_password_encrypted, undefined);
});