// #1873 proxy setup host helpers: restart proof from a fake /proc, the stale init-lock rules, // unit control over a fake systemctl, and receipts that carry no path or key. import test from 'node:test'; import assert from 'node:assert/strict'; import fs from 'node:fs'; import { join } from 'node:path'; import { tmpdir } from 'node:os'; import { createHash } from 'node:crypto'; import { execFileSync } from 'node:child_process'; import { PIN } from '../src/common.mjs'; import { installPaths } from '../src/settings.mjs'; import { processTree, pidListensOn, processStartMs, verifyRestart, initLockStatus, clearInitLock, initFiles, initState, fenceState, createUnitControl, releaseState, receiptFile, unitName, unitLog, serviceKeyState, receiptHistory, appendReceipt, LOG_LINES, HISTORY_LIMIT, } from '../src/admin.mjs'; import { secretValues } from '../src/redact.mjs'; const code = name => error => error.code === name; const scratch = t => { const dir = fs.mkdtempSync(join(tmpdir(), 'pa-')); t.after(() => fs.rmSync(dir, { recursive: true, force: true })); return dir; }; // A fake /proc: runner pid 100 (start tick 500), its child 101 listens on `port` via socket inode 5555. function fakeProc(t, { port = 8080, listener = 101, start = 500 } = {}) { const proc = join(scratch(t), 'proc'); const stat = (pid, ppid, ticks) => `${pid} (node) S ${ppid} 1 1 0 -1 0 0 0 0 0 0 0 0 0 20 0 1 0 ${ticks} 0 0\n`; fs.mkdirSync(join(proc, 'net'), { recursive: true }); fs.writeFileSync(join(proc, 'stat'), 'cpu 0\nbtime 1000\n'); for (const [pid, ppid, ticks] of [[1, 0, 1], [100, 1, start], [101, 100, start + 1], [200, 1, 1]]) { fs.mkdirSync(join(proc, String(pid), 'fd'), { recursive: true }); fs.writeFileSync(join(proc, String(pid), 'stat'), stat(pid, ppid, ticks)); } fs.symlinkSync('socket:[5555]', join(proc, String(listener), 'fd', '3')); fs.symlinkSync('/dev/null', join(proc, '100', 'fd', '0')); const hex = port.toString(16).toUpperCase().padStart(4, '0'); fs.writeFileSync(join(proc, 'net', 'tcp'), ' sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode\n' + ` 0: 0100007F:${hex} 00000000:0000 0A 00000000:00000000 00:00000000 00000000 1000 0 5555 1 0 100 0 0 10 0\n` + ` 1: 0100007F:${hex} 0100007F:9999 01 00000000:00000000 00:00000000 00000000 1000 0 7777 1 0 100 0 0 10 0\n`); return proc; } test('processTree follows parent links; pidListensOn finds a listener in a child of the unit main pid', t => { const proc = fakeProc(t); assert.deepEqual(processTree(100, { proc }).sort(), [100, 101]); assert.equal(pidListensOn(100, 8080, { proc }), true); assert.equal(pidListensOn(200, 8080, { proc }), false, 'an unrelated process does not count'); assert.equal(pidListensOn(100, 8081, { proc }), false, 'another port does not count'); assert.equal(processStartMs(100, { proc }), 1000 * 1000 + 5000); assert.equal(processStartMs(999, { proc }), null); }); const evidence = (over = {}) => ({ unit: 'mosaic-proxy.service', confirmed: true, before: { pid: 50, since: 10, active: 'active' }, after: { pid: 100, since: 20, active: 'active', listening: true }, observedAt: new Date(2000).toISOString(), ...over, }); const proof = { fence: { time: new Date(1000).toISOString() }, port: 8080, startMs: () => 1500, listens: (pid, port) => pid === 100 && port === 8080, now: () => 2000 }; test('verifyRestart accepts a confirmed restart to a new live listener started after the fence', () => { const result = verifyRestart(evidence(), proof); assert.deepEqual(result, { unit: 'mosaic-proxy.service', before: { pid: 50 }, after: { pid: 100, startedAt: new Date(1500).toISOString() }, observedAt: new Date(2000).toISOString(), listeningPort: 8080 }); }); test('verifyRestart refuses every unproved restart with proxy-restart-unconfirmed', () => { const cases = [ ['not confirmed', evidence({ confirmed: false }), proof], ['same pid', evidence({ before: { pid: 100, since: 10, active: 'active' } }), proof], ['extra field', { ...evidence(), forged: true }, proof], ['bad unit name', evidence({ unit: '../x.service' }), proof], ['stale observation', evidence({ observedAt: new Date(2000).toISOString() }), { ...proof, now: () => 2000 + 11 * 60 * 1000 }], ['process gone', evidence(), { ...proof, startMs: () => null }], ['started before the fence', evidence(), { ...proof, startMs: () => 900 }], ['fence without time', evidence(), { ...proof, fence: { invalid: true } }], ['not listening', evidence(), { ...proof, listens: () => false }], ['no port', evidence(), { ...proof, port: null }], ['not an object', 'restarted', proof], ]; for (const [name, value, options] of cases) assert.throws(() => verifyRestart(value, options), code('proxy-restart-unconfirmed'), name); }); function dirs(t) { const root = scratch(t); const configDir = join(root, 'config'), dataRoot = join(root, 'data'); fs.mkdirSync(configDir, { recursive: true, mode: 0o700 }); fs.mkdirSync(dataRoot, { recursive: true, mode: 0o700 }); return { root, configDir, dataRoot, files: initFiles(configDir, dataRoot) }; } test('init lock: absent refuses, held names each README blocker, clear needs every condition and writes a receipt', t => { const { root, configDir, dataRoot, files } = dirs(t); const stopped = { stopped: true, running: [] }; assert.deepEqual(initLockStatus({ configDir, dataRoot, buses: stopped }), { present: false, clearable: false, blockers: [] }); assert.throws(() => clearInitLock({ configDir, dataRoot, buses: stopped }), code('proxy-init-lock-absent')); fs.writeFileSync(files.lock, '', { mode: 0o600 }); fs.mkdirSync(files.proxyDir, { mode: 0o700 }); const held = initLockStatus({ configDir, dataRoot, buses: { stopped: false, running: ['organization acme'] } }); assert.equal(held.clearable, false); assert.deepEqual(held.blockers, ['bus running: organization acme', 'the proxy state directory exists']); assert.equal(JSON.stringify(held).includes(root), false, 'blockers name labels, never paths'); assert.throws(() => clearInitLock({ configDir, dataRoot, buses: { stopped: false, running: ['the instance bus'] } }), code('proxy-init-lock-held')); assert.throws(() => clearInitLock({ configDir, dataRoot, buses: stopped }), code('proxy-init-lock-held')); assert.equal(fs.existsSync(files.lock), true); fs.rmdirSync(files.proxyDir); assert.throws(() => clearInitLock({ configDir, dataRoot, buses: undefined }), code('proxy-init-lock-held'), 'no bus proof counts as running'); const receipt = clearInitLock({ configDir, dataRoot, buses: stopped, now: () => new Date(0) }); assert.equal(fs.existsSync(files.lock), false); assert.deepEqual(receipt, { op: 'init-lock.clear', time: new Date(0).toISOString(), conditions: ['bus stopped', 'no proxy.json', 'no management key file', 'no proxy state directory'] }); assert.deepEqual(fs.readFileSync(receiptFile(dataRoot), 'utf8').trim().split('\n').map(JSON.parse), [receipt]); assert.equal((fs.statSync(receiptFile(dataRoot)).mode & 0o777), 0o600); }); test('initState reports partial state from file presence and fenceState reads the fence without writing', t => { const { configDir, dataRoot, files } = dirs(t); assert.deepEqual(initState(configDir, dataRoot), { initialized: false, partial: false, problem: null, settings: null, files: { settings: false, key: false, proxyDir: false, lock: false }, lock: false }); fs.mkdirSync(files.proxyDir, { mode: 0o700 }); assert.equal(initState(configDir, dataRoot).partial, true); assert.equal(fenceState(dataRoot), null); fs.writeFileSync(join(files.proxyDir, 'mosaic-keys.uncertain'), JSON.stringify({ org: 'acme', op: 'apikey.add', time: '2026-11-11T00:00:00.000Z', pid: 7 }), { mode: 0o600 }); assert.deepEqual(fenceState(dataRoot), { org: 'acme', op: 'apikey.add', time: '2026-11-11T00:00:00.000Z', pid: 7 }); fs.chmodSync(join(files.proxyDir, 'mosaic-keys.uncertain'), 0o644); assert.deepEqual(fenceState(dataRoot), { invalid: true }); assert.deepEqual(fs.readdirSync(files.proxyDir), ['mosaic-keys.uncertain']); }); test('releaseState: nothing fetched names the next step without a path', t => { const { root, dataRoot } = dirs(t); const state = releaseState(dataRoot); assert.equal(state.fetched, false); assert.equal(state.verified, false); assert.equal(state.problem, 'proxy-install-missing'); assert.equal(JSON.stringify(state).includes(root), false); }); test('releaseState re-hashes a release file rewritten in place with its mtime set back', async t => { const { dataRoot } = dirs(t); const sha = bytes => createHash('sha256').update(bytes).digest('hex'); const binary = Buffer.from('made-up proxy binary 0001'), panel = Buffer.from('made-up panel'); const pin = { ...PIN, version: '0.0.0-test', binary: { ...PIN.binary, sha256: sha(binary) }, panel: { ...PIN.panel, sha256: sha(panel) } }; const paths = installPaths(dataRoot, pin); fs.mkdirSync(join(paths.dir, 'static'), { recursive: true }); fs.writeFileSync(paths.binary, binary, { mode: 0o755 }); fs.writeFileSync(paths.panel, panel); const when = 1700000000; for (const file of [paths.binary, paths.panel]) fs.utimesSync(file, when, when); assert.equal(releaseState(dataRoot, pin).verified, true); await new Promise(resolve => setTimeout(resolve, 50)); const before = fs.statSync(paths.binary, { bigint: true }); fs.writeFileSync(paths.binary, Buffer.from('made-up proxy binary 0002'), { flag: 'r+' }); fs.utimesSync(paths.binary, when, when); const after = fs.statSync(paths.binary, { bigint: true }); assert.deepEqual([after.ino, after.size, after.mtimeNs, after.mode], [before.ino, before.size, before.mtimeNs, before.mode], 'only ctime tells the files apart'); const state = releaseState(dataRoot, pin); assert.equal(state.verified, false); assert.equal(state.problem, 'proxy-install-invalid'); }); test('unit names follow the instance and refuse a bad instance', () => { assert.equal(unitName(null), 'mosaic-proxy.service'); assert.equal(unitName('dev'), 'mosaic-proxy.service'); assert.equal(unitName('uiorg'), 'mosaic-proxy-uiorg.service'); assert.throws(() => unitName('../x'), code('proxy-unit-usage')); }); // A fake systemctl / proxy-service.sh. `states` is the sequence `systemctl show` reports. function fakeUnit(states, { install = { code: 0, stdout: '', stderr: '' }, verbs = [] } = {}) { let i = 0; const run = async (command, args) => { if (command === 'systemctl' && args[1] === 'show') { const s = states[Math.min(i++, states.length - 1)]; return { code: 0, stdout: `LoadState=${s.load ?? 'loaded'}\nActiveState=${s.active}\nSubState=running\nMainPID=${s.pid ?? 0}\nExecMainStartTimestampMonotonic=${s.since ?? 0}\nNRestarts=0\n`, stderr: '' }; } if (command === 'systemctl') { verbs.push(args[1]); return { code: 0, stdout: '', stderr: '' }; } verbs.push(args.filter(a => !a.endsWith('proxy-service.sh')).join(' ')); return install; }; return createUnitControl({ instance: 'zz', port: () => 18432, run, probe: async () => true, waitMs: 0, pollMs: 0, now: () => new Date(0) }); } test('unit restart is confirmed only when a new main process is active and listening', async () => { const verbs = []; const control = fakeUnit([{ active: 'active', pid: 10, since: 5 }, { active: 'active', pid: 11, since: 6 }], { verbs }); const { evidence: e } = await control.restart(); assert.equal(e.confirmed, true); assert.deepEqual(e.before, { pid: 10, since: 5, active: 'active' }); assert.deepEqual(e.after, { pid: 11, since: 6, active: 'active', listening: true }); assert.equal(e.unit, 'mosaic-proxy-zz.service'); assert.deepEqual(verbs, ['restart']); const same = await fakeUnit([{ active: 'active', pid: 10, since: 5 }, { active: 'active', pid: 10, since: 5 }]).restart(); assert.equal(same.evidence.confirmed, false, 'the same process is not a restart'); const down = await fakeUnit([{ active: 'active', pid: 10, since: 5 }, { active: 'failed', pid: 0, since: 0 }]).restart(); assert.equal(down.evidence.confirmed, false, 'a failed unit is not a restart'); }); test('unit actions map proxy-service refusals by code and refuse a missing unit', async () => { await assert.rejects(fakeUnit([{ load: 'not-found', active: 'inactive' }]).start(), code('proxy-unit-missing')); await assert.rejects(fakeUnit([{ load: 'not-found', active: 'inactive' }]).restart(), code('proxy-unit-missing')); await assert.rejects(fakeUnit([{ active: 'inactive' }], { install: { code: 3, stdout: '', stderr: 'proxy-service: proxy-unit-exists\n' } }).install(), code('proxy-unit-exists')); await assert.rejects(fakeUnit([{ active: 'inactive' }], { install: { code: 3, stdout: '', stderr: 'proxy-service: /home/x secret detail\n' } }).install(), code('proxy-unit-failed')); await assert.rejects(fakeUnit([{ active: 'active', pid: 0 }, { active: 'failed', pid: 0 }]).start(), code('proxy-unit-unhealthy')); const verbs = []; const started = await fakeUnit([{ active: 'inactive' }, { active: 'active', pid: 9, since: 1 }], { verbs }).start(); assert.equal(started.healthy, true); assert.deepEqual(verbs, ['start']); assert.throws(() => createUnitControl({ unitDir: 'relative' }), code('proxy-unit-path')); }); // #1873 settings-backend A1: the reads behind the setup page's log, service key and history. // Planted keys, one of each Mosaic prefix and short enough that only the prefix rule finds them, // plus long ones of the real shapes. const TAIL = 'Ab3_dE5-fG7hJ9kL1mN3pQ5rS7tU9vW1xY3zA5bC7dE'; const PLANTED = ['msk-tag-qwertyu', 'mso-tag-acme-qwerty', 'mst-tag-triage-zxcvb', 'msp-tag-plmokn', `msk-k1a2-${TAIL}`, `mso-k1a2-acme-${TAIL}`, `mst-k1a2-triage-${TAIL}`, `msp-k1a2-${TAIL}`]; const ENV_SECRET = 'plainwordsonly'; const leaks = text => [...PLANTED, ...PLANTED.map(k => k.slice(4)), TAIL.slice(0, 10), ENV_SECRET].filter(bit => text.includes(bit)); function journal(stdout, { code: exit = 0, calls = [] } = {}) { return async (command, args, options) => { calls.push({ command, args, options }); if (stdout instanceof Error) throw stdout; return { code: exit, stdout, stderr: 'raw stderr msk-tag-qwertyu' }; }; } test('unitLog asks journalctl for the named unit only, clamps the line count, and shows no planted key', async () => { const calls = []; const lines = ['proxy listening on 127.0.0.1:18432', ...PLANTED.map(k => `upstream refused ${k} for model x`), `auth with ${ENV_SECRET} ok`, 'msk-tag-qwertyu', '', 'last line']; const result = await unitLog({ run: journal(lines.join('\n') + '\n', { calls }), unit: 'mosaic-proxy-zz.service', lines: 10000, env: { X: '1' }, secrets: secretValues({ PROXY_KEY: ENV_SECRET }) }); assert.deepEqual(calls[0].args, ['--user', '-u', 'mosaic-proxy-zz.service', '-n', String(LOG_LINES.max), '-o', 'cat', '--no-pager', '-q']); assert.equal(calls[0].command, 'journalctl'); assert.deepEqual(calls[0].options.env, { X: '1' }); assert.equal(result.unit, 'mosaic-proxy-zz.service'); assert.equal(result.lines[0], 'proxy listening on 127.0.0.1:18432', 'a line with nothing secret shows as it is'); assert.equal(result.lines.at(-1), 'last line'); assert.equal(result.lines.filter(l => l === 'upstream refused [redacted] for model x').length, PLANTED.length); assert.equal(result.redacted, PLANTED.length, 'shown lines with a redaction; dropped lines count in dropped'); assert.equal(result.dropped, 2, 'the env-secret line and the key-only line are dropped, the blank one is not counted'); assert.deepEqual(leaks(JSON.stringify(result)), []); // At least one line, and a line count that is not an integer is refused. await unitLog({ run: journal('x\n', { calls }), unit: 'mosaic-proxy.service', lines: 0 }); assert.equal(calls.at(-1).args[4], '1'); await assert.rejects(unitLog({ run: journal('x\n'), unit: 'mosaic-proxy.service', lines: 2.5 }), code('invalid-request')); await assert.rejects(unitLog({ run: journal('x\n'), unit: 'mosaic-proxy.service', lines: '5' }), code('invalid-request')); }); test('unitLog keeps only the last lines asked for and never takes a unit name it was not given by unitName', async () => { const many = Array.from({ length: 30 }, (_, i) => `line ${i}`).join('\n'); assert.deepEqual((await unitLog({ run: journal(many), unit: 'mosaic-proxy.service', lines: 3 })).lines, ['line 27', 'line 28', 'line 29']); for (const unit of ['sshd.service', 'mosaic-proxy.service; rm', '../mosaic-proxy.service', 'mosaic-proxy-A.service', undefined]) { await assert.rejects(unitLog({ run: journal('x'), unit, lines: 5 }), code('proxy-unit-usage'), String(unit)); } }); test('a journal that cannot be read refuses outcome-unknown with no lines and no other source', async () => { for (const run of [journal(Object.assign(new Error('spawn journalctl ENOENT'), { code: 'ENOENT' })), journal('partial msk-tag-qwertyu', { code: 1 }), async () => ({ code: 0, stdout: null }), async () => null]) { await assert.rejects(unitLog({ run, unit: 'mosaic-proxy.service', lines: 5 }), error => error.code === 'outcome-unknown' && !leaks(String(error.message) + JSON.stringify(error)).length); } }); test('a secret split across journal lines drops every line', async () => { const result = await unitLog({ run: journal('ok one\nplain\nwordsonly\nok two\n'), unit: 'mosaic-proxy.service', lines: 10, secrets: [ENV_SECRET] }); assert.deepEqual(result.lines, []); assert.equal(result.dropped, 4); }); test('createUnitControl.log runs unitLog for its own unit', async () => { const calls = []; const control = createUnitControl({ instance: 'zz', port: () => 1, run: journal('hello msk-tag-qwertyu\n', { calls }), probe: async () => true, waitMs: 0, pollMs: 0 }); assert.deepEqual(await control.log(5), { unit: 'mosaic-proxy-zz.service', lines: ['hello [redacted]'], redacted: 1, dropped: 0 }); assert.equal(calls[0].args[2], 'mosaic-proxy-zz.service'); }); test('serviceKeyState answers proxy.json\'s mtime and never opens or stats the key file', t => { const dir = scratch(t); assert.deepEqual(serviceKeyState(dir), { madeAt: null, renewedAt: null, renewal: 'not-built', problem: 'missing' }); const files = initFiles(dir, join(dir, 'data')); fs.writeFileSync(files.settings, '{}', { mode: 0o600 }); fs.mkdirSync(join(files.key, '..'), { recursive: true, mode: 0o700 }); fs.writeFileSync(files.key, 'msk-k1a2-' + TAIL, { mode: 0o600 }); fs.utimesSync(join(dir, 'proxy.json'), new Date(Date.UTC(2026, 10, 1, 8)), new Date(Date.UTC(2026, 10, 1, 8))); const spies = ['openSync', 'readFileSync', 'statSync', 'lstatSync', 'accessSync', 'existsSync', 'realpathSync', 'readdirSync'].map(name => t.mock.method(fs, name)); const state = serviceKeyState(dir); const seen = spies.flatMap(spy => spy.mock.calls.map(call => String(call.arguments[0]))); spies.forEach(spy => spy.mock.restore()); assert.deepEqual(state, { madeAt: '2026-11-01T08:00:00.000Z', renewedAt: null, renewal: 'not-built', problem: null }); assert.deepEqual(seen, [join(dir, 'proxy.json')]); assert.deepEqual(leaks(JSON.stringify(state)), []); }); test('serviceKeyState gives no date for a proxy.json that is a symlink, a directory or another user\'s', t => { const dir = scratch(t), other = scratch(t); fs.writeFileSync(join(other, 'real.json'), '{}'); fs.symlinkSync(join(other, 'real.json'), join(dir, 'proxy.json')); assert.deepEqual(serviceKeyState(dir), { madeAt: null, renewedAt: null, renewal: 'not-built', problem: 'unreadable' }); fs.rmSync(join(dir, 'proxy.json')); fs.mkdirSync(join(dir, 'proxy.json')); assert.equal(serviceKeyState(dir).problem, 'unreadable'); fs.rmSync(join(dir, 'proxy.json'), { recursive: true }); fs.writeFileSync(join(dir, 'proxy.json'), '{}'); assert.equal(serviceKeyState(dir, { uid: process.getuid() + 1 }).problem, 'unreadable'); assert.equal(serviceKeyState(dir).problem, null); }); // A receipt file with `count` entries; some lines padded so the file crosses several 64 KB chunks. function history(t, count, { pad = 0 } = {}) { const dataRoot = scratch(t); for (let i = 0; i < count; i++) appendReceipt(dataRoot, { time: new Date(i * 1000).toISOString(), op: 'fetch', n: i, ...(pad ? { note: 'word '.repeat(pad) } : {}) }); return dataRoot; } const pages = (dataRoot, limit, extra = {}) => { const seen = []; let before = null, guard = 0; do { const page = receiptHistory(dataRoot, { limit, before, ...extra }); seen.push(page.entries.map(e => e.n)); before = page.next; } while (before !== null && ++guard < 1000); return seen; }; test('receiptHistory pages newest first, oldest first within a page, each entry exactly once across chunks', t => { const dataRoot = history(t, 300, { pad: 150 }); assert.ok(fs.statSync(receiptFile(dataRoot)).size > 3 * 65536, 'the file spans several chunks'); const seen = pages(dataRoot, 7); assert.deepEqual(seen[0], [293, 294, 295, 296, 297, 298, 299]); assert.deepEqual(seen.flat().sort((a, b) => a - b), Array.from({ length: 300 }, (_, i) => i)); assert.equal(new Set(seen.flat()).size, 300); assert.deepEqual(seen.reverse().flat(), Array.from({ length: 300 }, (_, i) => i), 'pages read back to front are the whole history in order'); const first = receiptHistory(dataRoot); assert.equal(first.entries.length, HISTORY_LIMIT.default); assert.equal(receiptHistory(dataRoot, { limit: 1000 }).entries.length, HISTORY_LIMIT.max, 'limit is clamped'); assert.equal(receiptHistory(dataRoot, { limit: 0 }).entries.length, 1); assert.deepEqual(Object.keys(first.entries[0]).sort(), ['n', 'note', 'op', 'time']); }); test('receiptHistory skips a torn line and a partial last line, and a write after a page does not repeat or lose entries', t => { const dataRoot = history(t, 5); const file = receiptFile(dataRoot); const text = fs.readFileSync(file, 'utf8').split('\n'); text.splice(2, 0, '{"op":"torn', '[1,2]', '{"no":"op"}', 'x'.repeat(70000)); // The last line is a whole object whose newline is not written yet: it waits for the newline. fs.writeFileSync(file, text.join('\n') + '{"op":"partial","n":99}'); const first = receiptHistory(dataRoot, { limit: 2 }); assert.deepEqual(first.entries.map(e => e.n), [3, 4]); assert.deepEqual(receiptHistory(dataRoot, { limit: 1 }).entries.map(e => e.n), [4], 'not shown before its newline'); fs.appendFileSync(file, '\n'); appendReceipt(dataRoot, { op: 'fetch', n: 100 }); const rest = receiptHistory(dataRoot, { limit: 10, before: first.next }); assert.deepEqual(rest.entries.map(e => e.n), [0, 1, 2]); assert.equal(rest.next, null); assert.deepEqual(receiptHistory(dataRoot, { limit: 3 }).entries.map(e => e.n), [4, 99, 100], 'the finished line shows on the next newest read'); }); test('receiptHistory refuses a cursor that is not a line start, past the end, negative or not an integer', t => { const dataRoot = history(t, 3); const size = fs.statSync(receiptFile(dataRoot)).size; for (const before of [1, size + 1, -1, 1.5, '10', Number.MAX_SAFE_INTEGER + 2]) { assert.throws(() => receiptHistory(dataRoot, { before }), code('invalid-request'), String(before)); } assert.throws(() => receiptHistory(dataRoot, { limit: 'all' }), code('invalid-request')); assert.deepEqual(receiptHistory(dataRoot, { before: 0 }), { entries: [], next: null }); assert.equal(receiptHistory(dataRoot, { before: size }).entries.length, 3); }); test('receiptHistory withholds an entry whose fields hold an environment secret split across them', t => { const dataRoot = scratch(t); appendReceipt(dataRoot, { op: 'fetch', n: 1 }); appendReceipt(dataRoot, { op: 'x', a: 'plainword', b: 'sonly' }); appendReceipt(dataRoot, { op: 'x', plainw: 'ordsonly' }); appendReceipt(dataRoot, { op: 'x', list: ['plainwo', 'rdsonly'] }); appendReceipt(dataRoot, { op: 'fetch', n: 2 }); const all = receiptHistory(dataRoot, { limit: 10, secrets: secretValues({ PROXY_TOKEN: ENV_SECRET }) }); assert.deepEqual(all.entries, [{ op: 'fetch', n: 1 }, { withheld: true }, { withheld: true }, { withheld: true }, { op: 'fetch', n: 2 }]); assert.equal(receiptHistory(dataRoot, { limit: 10 }).entries[1].a, 'plainword', 'with no secrets nothing is withheld'); }); test('receiptHistory: a missing file is an empty history; a symlink, FIFO, directory, group-readable or foreign file refuses', t => { const dataRoot = scratch(t); assert.deepEqual(receiptHistory(dataRoot), { entries: [], next: null }); assert.throws(() => receiptHistory(dataRoot, { before: 5 }), code('invalid-request')); appendReceipt(dataRoot, { op: 'fetch' }); const file = receiptFile(dataRoot); fs.chmodSync(file, 0o640); assert.throws(() => receiptHistory(dataRoot), code('outcome-unknown')); fs.chmodSync(file, 0o600); assert.throws(() => receiptHistory(dataRoot, { uid: process.getuid() + 1 }), code('outcome-unknown')); assert.equal(receiptHistory(dataRoot).entries.length, 1); const elsewhere = join(scratch(t), 'x.jsonl'); fs.writeFileSync(elsewhere, '{"op":"planted"}\n', { mode: 0o600 }); fs.rmSync(file); fs.symlinkSync(elsewhere, file); assert.throws(() => receiptHistory(dataRoot), code('outcome-unknown')); fs.rmSync(file); fs.mkdirSync(file); assert.throws(() => receiptHistory(dataRoot), code('outcome-unknown')); fs.rmSync(file, { recursive: true }); execFileSync('mkfifo', ['-m', '600', file]); assert.throws(() => receiptHistory(dataRoot), code('outcome-unknown'), 'a FIFO is refused without blocking'); }); test('receiptHistory shows no planted key from any receipt field, nested value or key name', t => { const dataRoot = scratch(t); for (const key of PLANTED) appendReceipt(dataRoot, { time: new Date(0).toISOString(), op: 'init', note: `made ${key}`, nested: { list: [key, { deeper: key }] }, [key.replace(/-/g, '_')]: 1 }); appendReceipt(dataRoot, { op: 'init', env: ENV_SECRET, [`x${ENV_SECRET}`]: 1 }); appendReceipt(dataRoot, { op: PLANTED[1] }); const all = receiptHistory(dataRoot, { limit: 100, secrets: secretValues({ PROXY_TOKEN: ENV_SECRET }) }); assert.equal(all.entries.length, PLANTED.length + 2); assert.deepEqual(leaks(JSON.stringify(all)), []); assert.deepEqual(all.entries[0], { time: new Date(0).toISOString(), op: 'init', note: 'made [redacted]', nested: { list: ['[redacted]', { deeper: '[redacted]' }] } }); assert.deepEqual(all.entries.at(-2), { op: 'init', env: '[redacted]' }); assert.deepEqual(all.entries.at(-1), { op: '[redacted]' }); });