// Negative controls for the leak checker (DESIGN 10.1 "fault test", 10.3; M3 slice 5 / #20). // Every deliberate leak injected into a `-d:leakfault` build must make tools/leakcheck.nim fail, // and it must fail under the EXACT class set named here: a checker that flags everything would // prove nothing. The shipped build must contain no fault hook at all, and it must still pass. // // Classes: HIDDEN_TOKEN, GMONLY_TOKEN, WALLDATA, WITHHELD, NO_REMOVE, OWN_VIEW, OTHER_PLAYER, // EXPLORED, from slice 7 (#22) OWNER_PROP, GM_PROP, STATUS_SOURCE, and from slice 8 (#23) // ACTUAL_NAME, CHAR_LIST, CONTROLLER_CHANGE, CHAR_OWNER_PROP, and from Walls r1 (#58) ONEWAY and // (#60) MARKER_EARLY, MARKER_EXTRA, MARKER_OFF. // (The tile class lands with slice 9.) import test from 'node:test' import assert from 'node:assert/strict' import fs from 'node:fs' import { DatabaseSync } from 'node:sqlite' import path from 'node:path' import { runLeak, runChecker } from './leak.mjs' import { buildServer, gmKeyOf, makeStateDir, signIn, startServer, stopServer } from './withserver.mjs' import { openWs } from './lib.mjs' import { projectRoot } from './lib.mjs' // Checker output is per-process scratch; tools/test.sh concatenates the shards into the committed // results/faults.log after the Node phase (one write per run, not an append from every process). const logs = path.join(projectRoot, 'run', 'logs') // The 22 leak-fault cases are independent (own state dir, own server, own transcript) and each // costs ~4.8 s (one leak scenario + checker). tools/test.sh therefore runs this file as several // processes (`FFF_TEST_SHARDS`/`FFF_TEST_SHARD`) so the cases run in parallel without changing a // single test or assertion. Unset (a direct `node --test tools/fault.test.mjs`) = all cases here, // which is also what the shard maths below does for one shard. const SHARDS = Math.max(1, Number(process.env.FFF_TEST_SHARDS ?? 1)) const SHARD = Math.max(0, Number(process.env.FFF_TEST_SHARD ?? 0)) let faultCase = 0 // fault -> the exact set of classes the checker must report (nothing more, nothing less). // // `hidden` and `gmOnly` carry NO_REMOVE as well, and that is not a slack assertion: a state frame is // sent only when its content changes (T11, 6.4), so a token leaked by one of these faults that stops // changing leaves the client holding it with no message to correct it. From the client's side that // is indistinguishable from a withheld `token_gone`, which is what NO_REMOVE reports. Both // invariants really are broken by the fault. const FAULTS = { hidden: ['HIDDEN_TOKEN', 'NO_REMOVE'], gmOnly: ['GMONLY_TOKEN', 'NO_REMOVE'], walls: ['WALLDATA'], wallHeight: ['WALLDATA'], seenBy: ['WALLDATA'], // #75: the GM-only who-sees-it field in a player token frame oneWay: ['ONEWAY'], markerEarly: ['MARKER_EARLY'], markerExtra: ['MARKER_EXTRA'], markerOff: ['MARKER_OFF'], withhold: ['WITHHELD'], otherOwner: ['OTHER_PLAYER'], otherVision: ['OTHER_PLAYER'], otherExplored: ['OTHER_PLAYER'], noremove: ['NO_REMOVE'], explored: ['EXPLORED'], ownerProp: ['OWNER_PROP'], gmProp: ['GM_PROP'], statusSource: ['STATUS_SOURCE'], actualName: ['ACTUAL_NAME'], charList: ['CHAR_LIST'], controllerChange: ['CONTROLLER_CHANGE'], charOwnerProp: ['CHAR_OWNER_PROP'], } function classesOf(output) { return output.split('\n') .map(line => /^FAILCLASS ([A-Z_]+) \d+/.exec(line)) .filter(Boolean) .map(m => m[1]) .sort() } // The cases that do not belong to FAULTS run once, in shard 0, so a sharded run executes every test // exactly once across the processes (and a one-shard run is still the whole file). if (SHARD === 0) test('the shipped build carries no fault hook and passes the leak test', () => { const bin = buildServer() const bytes = fs.readFileSync(bin) assert.equal(bytes.includes(Buffer.from('LEAK_FAULT')), false, `${bin} contains the fault hook: a production binary must be incapable of leaking`) }) for (const [fault, expected] of Object.entries(FAULTS)) { if (faultCase++ % SHARDS !== SHARD) continue test(`fault ${fault}: caught as exactly ${expected.join(' ')}`, async () => { fs.mkdirSync(logs, { recursive: true }) const stateDir = makeStateDir() const gmKey = gmKeyOf(stateDir) const s = await startServer({ stateDir, defines: ['leakfault'], env: { LEAK_FAULT: fault } }) const transcript = path.join(stateDir, 'fault.jsonl') try { await runLeak({ origin: s.origin, gmKey, stateDir, transcript }) const check = runChecker(transcript, 'A') fs.appendFileSync(path.join(logs, `faults-${SHARD}.log`), `== fault ${fault}\n${check.output}\n`) assert.notEqual(check.status, 0, `the checker passed a leak (${fault}):\n${check.output}`) assert.deepEqual(classesOf(check.output), expected.sort(), `wrong classes for ${fault}:\n${check.output}`) } finally { await stopServer(s) fs.rmSync(stateDir, { recursive: true, force: true }) } }) } // #32: an escaping failure in intent handling must still answer the request. The `dispfault` build // is the only build with an injection point; the shipped binary must remain incapable of faulting. if (SHARD === 0) test('the shipped build carries no dispatch fault hook', () => { const bin = buildServer() const bytes = fs.readFileSync(bin) assert.equal(bytes.includes(Buffer.from('DISP_FAULT')), false, `${bin} contains the dispatch fault hook: a production binary must be incapable of faulting`) }) async function gmSession(s) { const gmKey = gmKeyOf(s.stateDir) const { cookie } = await signIn(s.origin, gmKey) const ws = await openWs(s.origin, cookie) const hello = await ws.waitText('hello') await ws.waitText('walls') return { ws, sceneId: hello.scene.id } } if (SHARD === 0) test('a CatchableError inside a locked mutation: one internal ack, then the server keeps serving', async () => { const stateDir = makeStateDir() const s = await startServer({ stateDir, defines: ['dispfault'], env: { DISP_FAULT: 'txn-catchable' } }) try { const gm = await gmSession(s) const tok = await gm.ws.request({ t: 'token.create', scene: gm.sceneId, kind: 'pc', pos: [100, 100], descriptive_name: 'a', actual_name: 'A' }) assert.equal(tok.ok, true, JSON.stringify(tok)) const bad = await gm.ws.request({ t: 'token.move', id: tok.id, pos: [150, 150] }) assert.equal(bad.ok, false) assert.equal(bad.code, 'internal', 'an escaping CatchableError is the internal code') assert.deepEqual(Object.keys(bad).sort(), ['code', 'n', 'ok', 'reqId', 't']) const acks = gm.ws.messages.filter(m => m.t === 'ack' && m.reqId === bad.reqId) assert.equal(acks.length, 1, 'exactly one ack for the failed intent') // Nothing from the failed intent is durable: the row still holds the create position. const db = new DatabaseSync(s.dbPath) assert.deepEqual({ ...db.prepare('SELECT x, y FROM entity WHERE id = ?').get(tok.id) }, { x: 100, y: 100 }) db.close() // One log event names the intent and the error class, never the message or payload. const log = s.log() assert.match(log, /ERROR intent_failed intent=token\.move reqId=\d+ class=ValueError message=unhandled/) assert.equal(log.includes('injected fault'), false, 'the exception message is not logged') // The transaction is closed: the next move on the same connection commits its own row. const good = await gm.ws.request({ t: 'token.move', id: tok.id, pos: [120, 120] }) assert.equal(good.ok, true, JSON.stringify(good)) // And a second, unaffected connection can mutate too. const gm2 = await gmSession(s) const good2 = await gm2.ws.request({ t: 'token.move', id: tok.id, pos: [130, 130] }) assert.equal(good2.ok, true, JSON.stringify(good2)) gm.ws.close(); gm2.ws.close() } finally { await stopServer(s) fs.rmSync(stateDir, { recursive: true, force: true }) } }) if (SHARD === 0) test('a Defect inside a locked mutation: one internal ack and no open transaction', async () => { const stateDir = makeStateDir() const s = await startServer({ stateDir, defines: ['dispfault'], env: { DISP_FAULT: 'txn-defect' } }) try { const gm = await gmSession(s) const tok = await gm.ws.request({ t: 'token.create', scene: gm.sceneId, kind: 'pc', pos: [100, 100], descriptive_name: 'a', actual_name: 'A' }) assert.equal(tok.ok, true, JSON.stringify(tok)) const bad = await gm.ws.request({ t: 'token.move', id: tok.id, pos: [150, 150] }) assert.equal(bad.code, 'internal', 'a Defect is answered like any other escaping failure') assert.equal(gm.ws.messages.filter(m => m.t === 'ack' && m.reqId === bad.reqId).length, 1) assert.equal(gm.ws.closeInfo, null, 'the connection stays usable by default') const good = await gm.ws.request({ t: 'token.move', id: tok.id, pos: [120, 120] }) assert.equal(good.ok, true, JSON.stringify(good)) gm.ws.close() } finally { await stopServer(s) fs.rmSync(stateDir, { recursive: true, force: true }) } }) if (SHARD === 0) test('a failure after the ack was enqueued never appends a second ack', async () => { const stateDir = makeStateDir() const s = await startServer({ stateDir, defines: ['dispfault'], env: { DISP_FAULT: 'after-ack' } }) try { const gm = await gmSession(s) const tok = await gm.ws.request({ t: 'token.create', scene: gm.sceneId, kind: 'pc', pos: [100, 100], descriptive_name: 'a', actual_name: 'A' }) assert.equal(tok.ok, true, JSON.stringify(tok)) const ack = await gm.ws.request({ t: 'token.move', id: tok.id, pos: [150, 150] }) assert.equal(ack.ok, true, 'the handler\'s own ack is the one the client sees') const all = gm.ws.messages.filter(m => m.t === 'ack' && m.reqId === ack.reqId) assert.equal(all.length, 1, 'the guard must not append an internal ack after a sent ack') assert.equal(all[0].code, undefined) const next = await gm.ws.request({ t: 'token.move', id: tok.id, pos: [120, 120] }) assert.equal(next.ok, true, JSON.stringify(next)) gm.ws.close() } finally { await stopServer(s) fs.rmSync(stateDir, { recursive: true, force: true }) } })