File size: 16,185 Bytes
b855ced
 
 
 
 
 
 
cce9364
b855ced
 
 
 
 
cce9364
b855ced
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cce9364
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b855ced
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
// Dead man's switch: every mode, against a real server process with a real
// data directory, key directory and extra paths. Each live test checks that
// the server exits, that keys, data and extra paths are gone, that a backup
// copy of the database taken beforehand can no longer be read, and that the
// server refuses to start again.

import { spawn, spawnSync } from 'node:child_process';
import { mkdtempSync, rmSync, mkdirSync, writeFileSync, readdirSync, existsSync, copyFileSync, chmodSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import assert from 'node:assert/strict';
import { withUrl } from './test-client.js';
import { Store } from './store.js';
import { generateOperatorKey, signOrder, verifyOrder, parseOperators, DeadMansSwitch, ORDER_MAX_AGE_MS, wipe } from './dms.js';

const results = [];
const test = async (name, fn) => {
  try { await fn(); results.push(['PASS', name]); } catch (e) { results.push(['FAIL', name, e.stack ?? String(e)]); }
};
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const root = mkdtempSync(join(tmpdir(), 'taper-dms-'));

// Three operators, each with a normal and a duress key.
const ops = Object.fromEntries(['ana', 'ben', 'cy'].map((n) => [n, { key: generateOperatorKey(), duress: generateOperatorKey() }]));
const operatorsText = Object.entries(ops).map(([n, o]) => `${n} ${o.key.publicKey} ${o.duress.publicKey}`).join('\n');
const operators = parseOperators(operatorsText);
const order = (name, action, { duress = false, server = 'localhost', ts } = {}) =>
  signOrder({ privatePem: (duress ? ops[name].duress : ops[name].key).privatePem, server, action, ts });

// --- orders, without a server ------------------------------------------------

await test('a signed order verifies, and names its operator', () => {
  const r = verifyOrder(order('ana', 'checkin'), { operators, server: 'localhost' });
  assert.deepEqual([r.name, r.action, r.duress], ['ana', 'checkin', false]);
  assert.equal(verifyOrder(order('ana', 'checkin', { duress: true }), { operators, server: 'localhost' }).duress, true);
});

await test('orders for another server, too old, unknown, altered or garbage are refused', () => {
  const v = (t) => verifyOrder(t, { operators, server: 'localhost' });
  assert.throws(() => v(order('ana', 'decommission', { server: 'other.example' })), /Bad signature/);
  assert.throws(() => v(order('ana', 'checkin', { ts: Date.now() - ORDER_MAX_AGE_MS - 1000 })), /too old/);
  const stranger = generateOperatorKey();
  assert.throws(() => v(signOrder({ privatePem: stranger.privatePem, server: 'localhost', action: 'decommission' })), /Unknown key/);
  const o = JSON.parse(Buffer.from(order('ana', 'checkin'), 'base64url'));
  o.a = 'decommission';
  assert.throws(() => v(Buffer.from(JSON.stringify(o)).toString('base64url')), /Bad signature/);
  for (const junk of ['', 'x', '{}', Buffer.from('[1]').toString('base64url')]) assert.throws(() => v(junk), /Not an order/);
});

await test('the operators file is checked', () => {
  assert.throws(() => parseOperators('ana notakey'), /not an Ed25519 public key/);
  assert.throws(() => parseOperators(`ana ${ops.ana.key.publicKey}\nana ${ops.ben.key.publicKey}`), /listed twice/);
  assert.throws(() => new DeadMansSwitch({ server: 's', operators, quorum: 4, onWipe() {} }), /QUORUM/);
  assert.throws(() => new DeadMansSwitch({ server: 's', deadhandMs: 1000, onWipe() {} }), /needs operators/);
});

await test('a replayed order is refused, and one operator voting twice is one vote', () => {
  const fired = [];
  const s = new DeadMansSwitch({ server: 'localhost', operators, quorum: 2, onWipe: (r) => fired.push(r), log() {} });
  const t = order('ana', 'decommission');
  assert.deepEqual(s.submit(t), { votes: 1, quorum: 2 });
  assert.throws(() => s.submit(t), /already used/);
  assert.deepEqual(s.submit(order('ana', 'decommission')), { votes: 1, quorum: 2 });
  assert.equal(fired.length, 0);
});

await test('quorum votes expire after the window', () => {
  let clock = Date.now();
  const s = new DeadMansSwitch({ server: 'localhost', operators, quorum: 2, windowMs: 60_000, onWipe() { throw new Error('fired'); }, log() {}, now: () => clock });
  s.submit(order('ana', 'decommission', { ts: clock }));
  clock += 61_000;
  assert.equal(s.submit(order('ben', 'decommission', { ts: clock })).votes, 1);
});

await test('a duress check-in records a check-in like a real one (M-3)', () => {
  let clock = 1_000_000;
  const s = new DeadMansSwitch({ server: 'localhost', operators, quorum: 2, onWipe() {}, log() {}, now: () => clock, duressDelayMs: 3_600_000 });
  clock += 5000;
  assert.deepEqual(s.submit(order('ana', 'checkin', { duress: true, ts: clock })), { checked_in: true });
  assert.equal(s.lastCheckin, clock);
  clearTimeout(s.duressTimer);
});

await test('a wipe carries on past a file it cannot shred (M-3)', () => {
  const root = mkdtempSync(join(tmpdir(), 'taper-shred-'));
  const dataDir = join(root, 'data');
  mkdirSync(join(dataDir, 'locked'), { recursive: true });
  writeFileSync(join(dataDir, 'a'), 'x');
  writeFileSync(join(dataDir, 'locked', 'b'), 'y');
  writeFileSync(join(dataDir, 'z'), 'x');
  chmodSync(join(dataDir, 'locked'), 0o500); // 'b' can be overwritten but not unlinked
  try {
    wipe({ dataDir });
    assert.ok(!existsSync(join(dataDir, 'a')) && !existsSync(join(dataDir, 'z')));
  } finally { chmodSync(join(dataDir, 'locked'), 0o700); rmSync(root, { recursive: true, force: true }); }
});

await test('store: keys exist for every unexpired period, and expired rows go even without a key file (M-5)', () => {
  const root = mkdtempSync(join(tmpdir(), 'taper-store-'));
  const st = new Store({ dataDir: join(root, 'd'), keyDir: join(root, 'k'), retentionMs: 3 * 86_400_000 });
  try {
    const now = st.period();
    assert.ok(st.key(now - 2), 'a period still inside retention can be sealed under');
    assert.equal(st.key(st.cutoff() - 1), null, 'an expired period is never recreated');
    st.db.prepare('INSERT INTO sealed (ns, k, period, iv, ct, tag) VALUES (?, ?, ?, ?, ?, ?)').run('ev', 'old', st.cutoff() - 5, Buffer.alloc(12), Buffer.alloc(1), Buffer.alloc(16));
    assert.deepEqual(st.shred(), []);
    assert.equal(st.db.prepare('SELECT COUNT(*) AS n FROM sealed').get().n, 0);
    st.setSecret('s', 'v1');
    st.setSecret('s', 'v2');
    assert.equal(st.secret('s', () => 'new'), 'v2');
  } finally { st.close(); rmSync(root, { recursive: true, force: true }); }
});

// --- live servers ------------------------------------------------------------

let port = 22000 + Math.floor(Math.random() * 1000);
const DMS_PATH = '/dms-AAAAAAAAAAAAAAAAAAAAAAAAAAAA';

/** A server with persistent data, an extra file and an extra directory to destroy. */
async function startServer(name, env = {}, { prepare } = {}) {
  const dir = join(root, name);
  const data = join(dir, 'data');
  const keys = join(dir, 'keys');
  const extraFile = join(dir, 'tls.key');
  const extraDir = join(dir, 'onion');
  mkdirSync(extraDir, { recursive: true });
  writeFileSync(extraFile, 'pretend TLS private key\n');
  writeFileSync(join(extraDir, 'hs_ed25519_secret_key'), 'pretend onion key\n');
  writeFileSync(join(dir, 'operators'), operatorsText);
  prepare?.({ dir, data, keys });
  const p = ++port;
  const socket = join(dir, 'admin.sock');
  const fullEnv = {
    ...process.env, PORT: String(p), TAPER_REGISTER_POW_BITS: '4', TAPER_ADMIN_SOCKET: socket,
    TAPER_DATA_DIR: data, TAPER_KEY_DIR: keys, TAPER_DMS_WIPE_PATHS: `${extraFile}:${extraDir}`,
    TAPER_DMS_OPERATORS: join(dir, 'operators'), TAPER_DMS_PATH: DMS_PATH, TAPER_DMS_CHECK_MS: '100', ...env,
  };
  const proc = spawn(process.execPath, ['index.js'], { env: fullEnv, stdio: ['ignore', 'pipe', 'pipe'] });
  const srv = { dir, data, keys, extraFile, extraDir, socket, port: p, proc, log: '', env: fullEnv };
  proc.stdout.on('data', (d) => { srv.log += d; });
  proc.stderr.on('data', (d) => { srv.log += d; });
  srv.exited = new Promise((r) => proc.on('exit', (code) => r(code)));
  srv.admin = (...args) => spawnSync(process.execPath, ['admin.js', '--socket', socket, ...args], { encoding: 'utf8' });
  srv.post = (body) => fetch(`http://127.0.0.1:${p}${DMS_PATH}`, { method: 'POST', body });
  const up = await Promise.race([
    new Promise((r) => { const t = setInterval(() => { if (srv.log.includes('Admin socket ready') && srv.log.includes('Taper gateway')) { clearInterval(t); r(true); } }, 50); }),
    srv.exited.then(() => false),
  ]);
  srv.started = up;
  return srv;
}

/** Put real data in: an account and a room, with sealed (encrypted) events. Then copy the database, as a backup would. */
async function populate(srv) {
  const Client = withUrl(`ws://127.0.0.1:${srv.port}/_taper/gateway/v1`);
  const c = await Client.connect();
  const auth = await c.register('dana', 'dana-dana-dana-dana');
  await c.identify(auth.access_token);
  await c.call('t.room.create', {});
  await sleep(200);
  const backup = join(srv.dir, 'backup.db');
  // The WAL holds recent writes; checkpoint by copying both, as a careless backup would.
  copyFileSync(join(srv.data, 'taper.db'), backup);
  if (existsSync(join(srv.data, 'taper.db-wal'))) copyFileSync(join(srv.data, 'taper.db-wal'), `${backup}-wal`);
  const before = sealedCount(srv.dir, 'backup.db', srv.keys);
  assert.ok(before > 0, 'the backup holds readable sealed data before the wipe');
  return c;
}

/** How many sealed records in a database copy can be decrypted with whatever keys are left. */
function sealedCount(dir, file, keys) {
  const copy = join(dir, `read-${Math.random().toString(36).slice(2)}`);
  mkdirSync(copy);
  copyFileSync(join(dir, file), join(copy, 'taper.db'));
  if (existsSync(join(dir, `${file}-wal`))) copyFileSync(join(dir, `${file}-wal`), join(copy, 'taper.db-wal'));
  mkdirSync(keys, { recursive: true });
  const s = new Store({ dataDir: copy, keyDir: keys, retentionMs: 1_814_400_000 });
  const total = s.db.prepare('SELECT ns FROM sealed GROUP BY ns').all().reduce((acc, { ns }) => acc + s.unsealAll(ns).length, 0);
  s.close();
  return total;
}

/** After a wipe: exit status 0, nothing left but the marker, backup unreadable, no restart. */
async function assertWiped(srv) {
  const code = await Promise.race([srv.exited, sleep(10_000).then(() => 'still running')]);
  assert.equal(code, 0, `server exit: ${code}\n${srv.log}`);
  assert.match(srv.log, /Decommissioned: \d+ paths destroyed\n/);
  assert.deepEqual(readdirSync(srv.keys), [], 'key directory empty');
  assert.deepEqual(readdirSync(srv.data), ['DECOMMISSIONED'], 'only the marker is left in the data directory');
  assert.equal(existsSync(srv.extraFile), false, 'extra file destroyed');
  assert.equal(existsSync(srv.extraDir), false, 'extra directory destroyed');
  assert.equal(existsSync(srv.socket), false, 'admin socket removed');
  assert.equal(sealedCount(srv.dir, 'backup.db', srv.keys), 0, 'a backup taken before the wipe can no longer be read');
  const again = spawnSync(process.execPath, ['index.js'], { env: srv.env, encoding: 'utf8', timeout: 10_000 });
  assert.equal(again.status, 0);
  assert.match(again.stderr, /was decommissioned/);
}

await test('command: a drill destroys nothing; a wrong confirmation is refused; the right one wipes everything', async () => {
  const srv = await startServer('command');
  assert.ok(srv.started, srv.log);
  await populate(srv);
  const drill = srv.admin('drill');
  assert.equal(drill.status, 0, drill.stderr);
  const plan = JSON.parse(drill.stdout).would_destroy;
  assert.ok(plan.some((p) => p.endsWith('taper.db')) && plan.includes(srv.extraFile), drill.stdout);
  assert.deepEqual(JSON.parse(drill.stdout).cannot_destroy, [], 'every path can be destroyed');
  assert.ok(existsSync(join(srv.data, 'taper.db')), 'drill left the data alone');
  assert.equal(srv.admin('decommission', 'wrong.example').status, 1);
  assert.equal(srv.admin('decommission').status, 2);
  const r = srv.admin('decommission', 'localhost');
  assert.equal(r.status, 0, r.stderr);
  await assertWiped(srv);
});

await test('quorum: 2 of 3 signed orders, one over the network; the network path otherwise looks absent', async () => {
  const srv = await startServer('quorum', { TAPER_DMS_QUORUM: '2' });
  assert.ok(srv.started, srv.log);
  await populate(srv);
  const cover = await fetch(`http://127.0.0.1:${srv.port}/no-such-page`);
  const coverBody = await cover.text();
  for (const bad of ['', 'garbage', order('ana', 'decommission', { server: 'other.example' })]) {
    const r = await srv.post(bad);
    assert.equal(r.status, cover.status);
    assert.equal(await r.text(), coverBody, 'an invalid order gets the same answer as a page that does not exist');
  }
  const first = srv.admin('order', order('ana', 'decommission'));
  assert.equal(first.status, 0, first.stderr);
  assert.deepEqual(JSON.parse(first.stdout), { votes: 1, quorum: 2 });
  await sleep(300);
  assert.ok(existsSync(join(srv.data, 'taper.db')), 'one vote is not enough');
  const second = await srv.post(order('ben', 'decommission'));
  assert.equal(second.status, 200);
  assert.deepEqual(await second.json(), { votes: 2, quorum: 2 });
  await assertWiped(srv);
});

await test('dead hand: check-ins keep it alive; silence past deadline and grace wipes it', async () => {
  const srv = await startServer('deadhand', { TAPER_DMS_DEADHAND_MS: '1500', TAPER_DMS_GRACE_MS: '1000' });
  assert.ok(srv.started, srv.log);
  await populate(srv);
  // Check in for 4 s, longer than deadline + grace, alternating local and signed network check-ins.
  for (let i = 0; i < 8; i++) {
    await sleep(500);
    if (i % 2) assert.equal(srv.admin('checkin').status, 0);
    else assert.deepEqual(await (await srv.post(order('cy', 'checkin'))).json(), { checked_in: true });
  }
  assert.ok(existsSync(join(srv.data, 'taper.db')), 'still alive while operators check in');
  assert.notEqual(JSON.parse(srv.admin('dms').stdout).dead_hand, 'off');
  await assertWiped(srv); // now silent
  assert.match(srv.log, /no check-in for .*wiping in/, 'a warning came first');
});

await test('dead hand: a deadline that passed while the server was down fires at start', async () => {
  const srv = await startServer('deadhand-boot', { TAPER_DMS_DEADHAND_MS: '60000', TAPER_DMS_GRACE_MS: '60000' }, {
    prepare: ({ keys }) => { mkdirSync(keys, { recursive: true }); writeFileSync(join(keys, 'dms-state.json'), JSON.stringify({ last_checkin_ts: Date.now() - 300_000 })); },
  });
  const code = await Promise.race([srv.exited, sleep(10_000).then(() => 'still running')]);
  assert.equal(code, 0, srv.log);
  assert.deepEqual(readdirSync(srv.data), ['DECOMMISSIONED']);
  assert.equal(existsSync(srv.extraDir), false);
});

await test('duress: the duress check-in answers exactly like a real one, then wipes; a real check-in cannot stop it', async () => {
  const srv = await startServer('duress', { TAPER_DMS_DEADHAND_MS: '3600000', TAPER_DMS_DURESS_DELAY_MS: '1500' });
  assert.ok(srv.started, srv.log);
  await populate(srv);
  const real = await srv.post(order('ana', 'checkin'));
  const statusBefore = JSON.parse(srv.admin('dms').stdout);
  const forced = await srv.post(order('ana', 'checkin', { duress: true }));
  assert.equal(forced.status, real.status);
  assert.deepEqual(await forced.json(), await real.json());
  const statusAfter = JSON.parse(srv.admin('dms').stdout);
  delete statusBefore.dead_hand; delete statusAfter.dead_hand; // the check-in time moves; nothing else may differ
  assert.deepEqual(statusAfter, statusBefore, 'status does not reveal a pending duress wipe');
  assert.doesNotMatch(srv.log, /switch|wip/i, `nothing in the log yet either:\n${srv.log}`);
  assert.equal(srv.admin('checkin').status, 0);
  await assertWiped(srv);
});

rmSync(root, { recursive: true, force: true });
let failed = 0;
for (const [status, name, detail] of results) {
  console.log(`${status}  ${name}`);
  if (status === 'FAIL') { failed++; console.log(`      ${detail.split('\n').slice(0, 12).join('\n      ')}`); }
}
console.log(`\n${results.length - failed}/${results.length} passed`);
process.exit(failed ? 1 : 0);