"use strict"; // Tests for the concurrent-rotation desync on POST /api/nodes/:id/rotate-token. // // The pre-fix route authenticated the daemon push (/v1/token/rotate) with a // pre-lock node snapshot and serialized ONLY the database persist under the // node's row lock (node-ports:). The daemon (main.go handleTokenRotate) // keeps every retired token accepted for a 10-minute grace window, so two // rotations issued nearly simultaneously BOTH succeeded against the daemon // even though the second push invalidated the first — and because the HTTP // response order (which drove the persist-enqueue order) can invert relative // to the daemon's adoption order, the panel could commit T1 while the daemon // held T2. The node then worked only until the grace expired, dropped // offline, and needed a config.yml re-deploy. No secret was exposed — pure // availability — which is exactly why it would have lingered. // // Remediation contract locked here: // - The WHOLE credential swap (fresh in-lock re-read -> daemon push -> // persist) runs under ONE withKeyedLock(`node-ports:`) acquisition, // so push adoption order and persist commit order cannot invert. // - Each rotation re-reads the row inside the lock and authenticates its // daemon push with the token the previous rotation persisted — never with // a pre-lock snapshot. // - The persist goes through nodesRouter.rotateNodeTokenPrelocked; the lock // is not reentrant, so calling rotateNodeToken from inside it would // deadlock (the source-contract test guards against reintroducing both // the race and that deadlock). // - The startup integrity gate's automatic legacy-token rotation runs the // same fresh-read -> push -> persist swap under the injected node row // lock (withNodeLock -> withKeyedLock(`node-ports:`)): the gate runs // before the HTTP listeners open, but the pending-disk applier's module- // load interval timer does not, and its full-row saveNode would revert a // gate rotation that landed between its in-lock re-read and its save. // - Response parity with the pre-fix route: 200 {ok, token, tokenId} // (+ reconfigureRequired/detail on the invalidated-credential path), // 404 node not found, 409 daemon unsupported, 502 daemon rejected // (+ detail), 500 persist failed. // // index.js boots servers on require, so the route handler is sliced out of // the source and evaluated in a vm sandbox (same technique as // webhook-config-write-lock.test.js). The sandbox binds the REAL nodes.js // persistence path (findNodeByIdOrName / rotateNodeTokenPrelocked over a // stubbed db.query) and a daemon simulator replicating main.go's authOK // (current token + 10-minute old-token grace) and handleTokenRotate swap. const test = require("node:test"); const assert = require("node:assert"); const fs = require("node:fs"); const path = require("node:path"); const vm = require("node:vm"); const crypto = require("node:crypto"); if (!process.env.SESSION_SECRET || process.env.SESSION_SECRET.length < 32) { process.env.SESSION_SECRET = "adpanel-node-token-rotation-test-secret-0123456789"; } const nodeTokenCrypto = require("../utils/node-token-crypto"); const db = require("../db"); const nodesModule = require("../nodes"); const { verifyNodeTokenIntegrity } = require("../utils/node-token-integrity"); const { withKeyedLock } = require("../utils/keyed-async-lock"); const INDEX_JS = path.join(__dirname, "..", "index.js"); const NODES_JS = path.join(__dirname, "..", "nodes.js"); const ROUTE_MARKER = 'app.post("/api/nodes/:id/rotate-token"'; const NEXT_ROUTE_MARKER = 'app.get("/api/nodes/:id/disks"'; const T0 = "adpnt_initial000000000000000000000000"; function extractRouteSlice() { const source = fs.readFileSync(INDEX_JS, "utf8"); const start = source.indexOf(ROUTE_MARKER); assert.ok(start >= 0, "rotate-token route must exist in index.js"); const end = source.indexOf(NEXT_ROUTE_MARKER, start); assert.ok(end > start, "rotate-token route slice must be bounded"); return source.slice(start, end); } // Mirrors main.go: authOK accepts the current token and the previous one // until its 10-minute grace expires; handleTokenRotate persists then swaps // (retiring the current token to the grace slot). function makeDaemon(initialToken) { return { token: initialToken, oldToken: null, oldTokenExp: 0, unsupported: false, adopted: 0, rotate(bearer, newToken) { if (this.unsupported) return { status: 404, json: { ok: false, error: "not found" } }; const valid = bearer === this.token || (bearer === this.oldToken && Date.now() < this.oldTokenExp); if (!valid) return { status: 401, json: { ok: false, error: "unauthorized" } }; this.oldToken = this.token; this.oldTokenExp = Date.now() + 10 * 60 * 1000; // main.go tokenGraceDuration this.token = newToken; this.adopted += 1; return { status: 200, json: { ok: true, graceSeconds: 600 } }; }, }; } function seedRow(token) { return { id: "node-1", uuid: "uuid-node-1", name: "edge-01", address: "203.0.113.10", ram_mb: 0, disk_gb: 0, ports: "{}", token_id: "tok-id-1", // Token at rest is the GCM envelope, exactly as saveNode writes it. token: token ? nodeTokenCrypto.encryptNodeToken(token) : null, token_status: token ? nodeTokenCrypto.TOKEN_STATUS_OK : nodeTokenCrypto.TOKEN_STATUS_ROTATE_REQUIRED, created_at: Date.now(), api_port: 8080, sftp_port: 2022, port_ok: 1, last_seen: Date.now(), last_check: Date.now(), online: 1, build_config: "{}", max_upload_mb: 10240, }; } function makeHarness() { const state = { store: new Map(), // Chronological log of daemon adoptions and database persists — the true // interleaving, since JS is single-threaded. events: [], daemon: makeDaemon(T0), // FIFO of delays applied BEFORE the daemon adopts each push (push // initiation -> adoption latency). Empty list = no delay. pushPreDelays: [], // FIFO of delays applied AFTER the daemon adopted but BEFORE the panel // receives the response — HTTP transit jitter, the ingredient that let // the pre-fix route persist in adoption-inverted order. holdAfterAdoptMs: [], failNextPersist: false, }; state.store.set("node-1", seedRow(T0)); state.origQuery = db.query; db.query = async (sql, params = []) => { if (sql.includes("FROM nodes WHERE")) { // nodes.js findNodeByIdOrName: SELECT * FROM nodes WHERE id = ? OR uuid = ? OR LOWER(name) = ? const key = String(params[0] || "").trim().toLowerCase(); for (const row of state.store.values()) { if ( String(row.id).toLowerCase() === key || String(row.uuid || "").toLowerCase() === key || String(row.name || "").toLowerCase() === key ) return [row]; } return []; } if (sql.includes("UPDATE nodes SET")) { // saveNode column order: uuid,name,address,ram,disk,ports,token_id, // token(7),token_status(8),created,api,sftp,port_ok,last_seen,last_check, // online,build_config,max_upload(17), WHERE id(18). if (state.failNextPersist) { state.failNextPersist = false; throw new Error("simulated database outage"); } const row = state.store.get(String(params[18])); if (!row) return []; row.uuid = params[0]; row.name = params[1]; row.address = params[2]; row.token_id = params[6]; row.token = params[7]; row.token_status = params[8]; state.events.push({ type: "persist", token: nodeTokenCrypto.decryptNodeToken(params[7]), token_status: params[8], }); return []; } return []; }; state.handler = null; state.firstLookupOverrides = []; const sandbox = { app: { post: (_route, ...handlers) => { state.handler = handlers.at(-1); } }, sessionRevoke2faRateLimiter: {}, isAdmin: async () => true, findUserByEmail: async () => ({ email: "admin@test.local", admin: true }), // The route's pre-lock lookup and its in-lock re-read both go through the // real nodes.js loader (over the stubbed db); tests may inject one-shot // overrides to simulate the row vanishing mid-request. findNodeByIdOrName: async (id) => { if (state.firstLookupOverrides.length) return state.firstLookupOverrides.shift()(id); return nodesModule.findNodeByIdOrName(id); }, requireDestructiveActionStepUp: async () => ({ ok: true }), nodeStepUpScopeKey: () => "node-step-up-scope", crypto, withKeyedLock, nodesRouter: nodesModule, callNodeUpdateApi: async (node, suffix, opts = {}) => { if (suffix !== "/v1/token/rotate") throw new Error(`unexpected suffix ${suffix}`); const delay = state.pushPreDelays.shift() || 0; if (delay) await new Promise((r) => setTimeout(r, delay)); const bearer = (node && node.token) || null; const pushed = (opts.body && opts.body.token) || null; const outcome = state.daemon.rotate(bearer, pushed); state.events.push({ type: "push", bearer, pushed, status: outcome.status }); const hold = state.holdAfterAdoptMs.shift() || 0; if (hold) await new Promise((r) => setTimeout(r, hold)); return outcome; }, recordActivity: async () => {}, console: { log() { }, warn() { }, error() { }, debug() { } }, }; vm.runInContext(extractRouteSlice(), vm.createContext(sandbox), { filename: "rotate-token-route-slice.js", }); assert.ok(typeof state.handler === "function", "route handler must be captured"); state.rotate = (nodeId = "node-1") => { const req = { session: { user: "admin@test.local" }, params: { id: nodeId } }; const res = { statusCode: null, body: null, status(code) { this.statusCode = code; return this; }, // Express sends res.json() with the implicit 200 when no status was set. json(o) { if (this.statusCode === null) this.statusCode = 200; this.body = o; return o; }, }; return state.handler(req, res, (err) => { res.nextError = err; }).then(() => res); }; state.restore = () => { db.query = state.origQuery; }; return state; } async function withHarness(fn) { const state = makeHarness(); try { await fn(state); } finally { state.restore(); } } const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); test("concurrent rotations: push adoption order and persist commit order cannot invert (panel never holds a grace-only token)", async () => { await withHarness(async (state) => { // Adversarial timing that inverted the orders on the pre-fix route: // - A initiates its daemon push first and ADOPTS T1 immediately (no // pre-delay), but the HTTP response takes ~60ms to travel back, so A // cannot persist until t=60ms. // - B starts 30ms in with a snapshot of the pre-rotation row, pushes // and ADOPTS T2 at t=30ms, and its response travels instantly. // Pre-fix: adoption order T1,T2 but persist order T2,T1 -> the panel held // T1 while the daemon held T2; the node died when the grace expired. state.pushPreDelays = [0, 0]; state.holdAfterAdoptMs = [60, 0]; const resAPromise = state.rotate(); await sleep(30); // B starts while A's adopted push is still "in flight" const resBPromise = state.rotate(); const [resA, resB] = await Promise.all([resAPromise, resBPromise]); assert.equal(resA.statusCode, 200, "rotation A must succeed"); assert.equal(resB.statusCode, 200, "rotation B must succeed"); assert.ok(resA.body.ok && resB.body.ok, "both rotations must report ok"); assert.notEqual(resA.body.token, resB.body.token, "each rotation must mint a distinct token"); // Serialization fingerprint: the swap runs push->persist as one unit, so // the event log strictly alternates. The pre-fix route produced // [push, push, persist, persist] under this timing. assert.deepEqual( state.events.map((e) => e.type), ["push", "persist", "push", "persist"], "each daemon push must be followed immediately by its own persist" ); const [push1, persist1, push2, persist2] = state.events; assert.equal(persist1.token, push1.pushed, "the first adopter's token is what gets committed first"); // Second push authenticated with the token the FIRST rotation persisted: // proves the in-lock re-read, not a pre-lock snapshot, drives the push. assert.equal(push2.bearer, push1.pushed, "the second push must authenticate with the first rotation's persisted token"); // THE invariant: the panel's final credential is the daemon's final // current credential — valid forever, not merely until grace expiry. assert.equal(persist2.token, state.daemon.token, "the last persisted token must be the daemon's current token"); assert.equal(persist2.token, push2.pushed, "the last persisted token must be the last adopted token"); assert.equal( nodeTokenCrypto.decryptNodeToken(state.store.get("node-1").token), state.daemon.token, "the stored row must hold the daemon's current token" ); assert.equal(state.daemon.adopted, 2, "both pushes must have been adopted"); // The winning response is the one whose push landed last. assert.ok( [resA.body.token, resB.body.token].includes(state.daemon.token), "the daemon's final token must be one of the issued ones" ); assert.equal(persist2.token_status, nodeTokenCrypto.TOKEN_STATUS_OK, "rotation clears the rotate_required flag"); }); }); test("concurrent rotations remain consistent when both responses return in adoption order", async () => { await withHarness(async (state) => { // No jitter: B starts only after A adopted AND persisted. Baseline // sequential-case sanity for the same invariant. const resA = await state.rotate(); assert.equal(resA.statusCode, 200); const resB = await state.rotate(); assert.equal(resB.statusCode, 200); assert.deepEqual(state.events.map((e) => e.type), ["push", "persist", "push", "persist"]); assert.equal(state.events[2].bearer, state.events[1].token, "the second rotation must push against the first rotation's credential"); assert.equal(state.events[3].token, state.daemon.token, "panel and daemon must converge on the last rotation"); assert.equal( nodeTokenCrypto.decryptNodeToken(state.store.get("node-1").token), state.daemon.token ); }); }); test("a node deleted while the request sits queued 404s inside the lock and never reaches the daemon", async () => { await withHarness(async (state) => { // One-shot override: the route's pre-lock lookup still sees the node, // the in-lock re-read (second call) finds it gone. state.firstLookupOverrides.push(() => nodesModule.findNodeByIdOrName("node-1")); state.firstLookupOverrides.push(() => null); const res = await state.rotate(); assert.equal(res.statusCode, 404, "the in-lock re-read must 404"); assert.deepEqual(res.body, { error: "node not found" }); assert.equal(state.events.length, 0, "no daemon push and no persist may happen for a deleted node"); assert.equal(state.daemon.adopted, 0, "the daemon must not be handed a credential for an untracked node"); }); }); test("invalidated credential (startup integrity gate): panel-side re-issue never touches the daemon and flags reconfigure", async () => { await withHarness(async (state) => { state.store.set("node-1", seedRow(null)); // token NULL, rotate_required const res = await state.rotate(); assert.equal(res.statusCode, 200); assert.equal(res.body.ok, true); assert.equal(res.body.reconfigureRequired, true, "the admin must be told to re-deploy config.yml"); assert.ok(typeof res.body.detail === "string" && res.body.detail.length > 0, "guidance detail must be present"); assert.ok(res.body.token.startsWith("adpnt_"), "a fresh token must be issued"); assert.equal(state.events.filter((e) => e.type === "push").length, 0, "no daemon push may happen without a usable bearer secret"); const row = state.store.get("node-1"); assert.equal(nodeTokenCrypto.decryptNodeToken(row.token), res.body.token, "the re-issued token must be persisted"); assert.equal(row.token_status, nodeTokenCrypto.TOKEN_STATUS_OK, "the rotate_required flag must clear"); assert.equal(res.body.tokenId, row.token_id, "the response must carry the row's token id"); }); }); test("startup integrity gate: the legacy-token rotation swap serializes under the injected node row lock", async () => { // The gate rotates a rotate_required row at startup: push a fresh credential // authenticated with the legacy value, then persist it. index.js applies the // SAME node-ports: keyed lock the rotate-token endpoint uses (see the // withNodeLock injection at the verifyNodeTokenIntegrity call site), because // the pending-disk applier's full-row saveNode is a module-load interval // timer that can run mid-startup — pre-listen does not mean writers-free. // These subtests pin both directions with an applier-style full-row writer. const T_LEGACY = "legacy_plain_credential_0123456789abcdef"; function makeGateHarness() { const storeRow = { id: "node-g1", name: "edge-gate", // At rest the legacy value is already the GCM envelope the migration wrote. token: nodeTokenCrypto.encryptNodeToken(T_LEGACY), token_status: nodeTokenCrypto.TOKEN_STATUS_ROTATE_REQUIRED, }; // The daemon still runs the legacy plaintext value (it predates the migration). const daemon = makeDaemon(T_LEGACY); const events = []; const dbStub = { async query(sql, params = []) { if (sql.startsWith("SELECT")) return [storeRow]; if (sql.startsWith("UPDATE nodes SET token = ?, token_status = ?")) { storeRow.token = params[0]; storeRow.token_status = params[1]; events.push({ type: "gate-persist", token: nodeTokenCrypto.decryptNodeToken(params[0]) }); return []; } return []; }, }; const getNodeByIdOrName = async (id) => { if (String(id) !== storeRow.id) return null; return { id: storeRow.id, name: storeRow.name, token: nodeTokenCrypto.decryptNodeToken(storeRow.token), }; }; return { storeRow, daemon, events, dbStub, getNodeByIdOrName }; } // (a) WITHOUT the injected lock (the pre-fix shape): an applier-style // full-row writer whose save straddles the gate's persist resurrects the // legacy credential — the daemon holds the rotated token while the panel // row is reverted to the grace-only legacy value. { const h = makeGateHarness(); let releasePush; const pushHold = new Promise((r) => { releasePush = r; }); let releaseApplierSave; const applierSaveHold = new Promise((r) => { releaseApplierSave = r; }); const gatePromise = verifyNodeTokenIntegrity({ db: h.dbStub, getNodeByIdOrName: h.getNodeByIdOrName, rotateNodeCredential: async (node, newToken) => { const outcome = h.daemon.rotate(node.token, newToken); h.events.push({ type: "push", bearer: node.token, pushed: newToken, status: outcome.status }); await pushHold; // gate push "in flight" while the applier runs return outcome.status === 200 && outcome.json.ok; }, logger: { log() { }, warn() { }, error() { } }, }); await sleep(5); // the gate is now parked inside its push (async () => { // Unlocked applier interleave: snapshot BEFORE the gate persists, // full-row save AFTER — the straddle the node row lock prevents. const snapshot = { ...h.storeRow }; await applierSaveHold; h.storeRow.token = snapshot.token; h.storeRow.token_status = snapshot.token_status; h.events.push({ type: "applier-full-row-save", token: nodeTokenCrypto.decryptNodeToken(snapshot.token) }); })(); releasePush(); await sleep(5); // the gate's persist commits while the applier save is parked releaseApplierSave(); const summary = await gatePromise; assert.equal(summary.rotated, 1, "the gate pushed and persisted the rotation"); assert.notEqual(h.daemon.token, T_LEGACY, "the daemon adopted the rotated token"); assert.deepEqual( h.events.map((e) => e.type), ["push", "gate-persist", "applier-full-row-save"], "unlocked: the applier's stale full-row save landed after the gate's persist" ); assert.equal( nodeTokenCrypto.decryptNodeToken(h.storeRow.token), T_LEGACY, "unlocked: the stale applier save resurrected the legacy credential (the race the lock closes)" ); } // (b) WITH the injected lock: the applier's full-row save queues behind the // gate's swap, so its in-lock re-read observes the ROTATED credential and // the panel row ends holding the daemon's current token. { const h = makeGateHarness(); let releasePush; const pushHold = new Promise((r) => { releasePush = r; }); const gatePromise = verifyNodeTokenIntegrity({ db: h.dbStub, getNodeByIdOrName: h.getNodeByIdOrName, rotateNodeCredential: async (node, newToken) => { const outcome = h.daemon.rotate(node.token, newToken); h.events.push({ type: "push", bearer: node.token, pushed: newToken, status: outcome.status }); await pushHold; // the swap holds the node lock across the daemon push return outcome.status === 200 && outcome.json.ok; }, withNodeLock: (nodeId, task) => withKeyedLock(`node-ports:${nodeId}`, task), logger: { log() { }, warn() { }, error() { } }, }); await sleep(5); // the gate acquired the node lock and is parked in its push let applierReadToken = null; const applierPromise = withKeyedLock(`node-ports:${h.storeRow.id}`, async () => { // index.js applyPendingNodeDisks(): fresh re-read INSIDE the lock, then // a full-row saveNode of exactly what it read. const snapshot = { ...h.storeRow }; applierReadToken = nodeTokenCrypto.decryptNodeToken(snapshot.token); h.storeRow.token = snapshot.token; h.storeRow.token_status = snapshot.token_status; h.events.push({ type: "applier-full-row-save", token: applierReadToken }); }); releasePush(); await Promise.all([gatePromise, applierPromise]); assert.equal(h.daemon.adopted, 1, "the gate's push was adopted once"); assert.deepEqual( h.events.map((e) => e.type), ["push", "gate-persist", "applier-full-row-save"], "serialized: the applier's save can only land after the gate's swap completed" ); assert.equal( applierReadToken, h.daemon.token, "the queued applier's in-lock re-read observed the rotated credential" ); assert.equal( nodeTokenCrypto.decryptNodeToken(h.storeRow.token), h.daemon.token, "the panel row ends holding the daemon's current token" ); assert.equal(h.storeRow.token_status, nodeTokenCrypto.TOKEN_STATUS_OK, "the rotate_required flag cleared"); } }); test("a daemon without rotation support yields 409 and leaves the credential untouched", async () => { await withHarness(async (state) => { state.daemon.unsupported = true; const res = await state.rotate(); assert.equal(res.statusCode, 409); assert.match(res.body.error, /does not support token rotation/); assert.equal(state.events.filter((e) => e.type === "persist").length, 0, "nothing may be persisted"); assert.equal( nodeTokenCrypto.decryptNodeToken(state.store.get("node-1").token), T0, "the stored token must be unchanged" ); assert.equal(state.daemon.token, T0, "the daemon token must be unchanged"); }); }); test("a daemon that rejects the push (grace expired / foreign credential) yields 502 with detail and persists nothing", async () => { await withHarness(async (state) => { // The daemon already holds a credential the panel does not know (e.g. an // earlier swap whose grace expired, or a manual config.yml redeploy): // the panel's T0 no longer authenticates. state.daemon = makeDaemon("adpnt_foreign00000000000000000000000"); const res = await state.rotate(); assert.equal(res.statusCode, 502); assert.equal(res.body.error, "node rejected token rotation"); assert.equal(res.body.detail, "unauthorized"); assert.equal(state.events.filter((e) => e.type === "persist").length, 0, "nothing may be persisted"); assert.equal( nodeTokenCrypto.decryptNodeToken(state.store.get("node-1").token), T0, "the stored token must be unchanged" ); }); }); test("a persist failure after a successful push surfaces via the error pipeline with no panel-side commit (residual crash-window documented)", async () => { await withHarness(async (state) => { // A database outage after the daemon already adopted the new token is a // crash-consistency window no single-request fix can close (the panel and // daemon have no shared transaction). The route must not paper over it: // the error reaches the express error pipeline, the panel row keeps the // old credential, and the daemon's 10-minute old-token grace plus the // startup integrity gate remain the recovery paths — exactly the pre-fix // behavior for this failure mode. state.failNextPersist = true; const res = await state.rotate(); assert.ok(res.nextError, "a persist throw must reach next(err), not be swallowed"); assert.match(String(res.nextError && res.nextError.message), /simulated database outage/); assert.equal(res.statusCode, null, "no route-level response may be sent"); assert.equal( nodeTokenCrypto.decryptNodeToken(state.store.get("node-1").token), T0, "the panel row keeps the old credential" ); assert.equal(state.daemon.token !== T0, true, "the daemon adopted the new token (documented residual window)"); }); }); test("source contract: the whole swap is locked, the push precedes the prelocked persist, and no deadlocking re-acquire exists", () => { const source = fs.readFileSync(INDEX_JS, "utf8"); const start = source.indexOf(ROUTE_MARKER); assert.ok(start >= 0, "rotate-token route must exist"); const end = source.indexOf(NEXT_ROUTE_MARKER, start); const slice = source.slice(start, end); const stepUpAt = slice.indexOf("requireDestructiveActionStepUp"); const lockAt = slice.indexOf("withKeyedLock(`node-ports:"); const pushAt = slice.indexOf("callNodeUpdateApi(fresh"); // The route has TWO persist call sites (the invalidated-credential branch // legitimately appears earlier in the source); the push-ordered one is the // last of them. const persistAt = slice.lastIndexOf("rotateNodeTokenPrelocked(fresh.id"); const recheckAt = slice.indexOf("findNodeByIdOrName(node.id)"); assert.ok(stepUpAt >= 0 && stepUpAt < lockAt, "step-up must gate the request before the lock is taken"); assert.ok(lockAt >= 0, "the route must take the node row lock itself"); assert.ok(recheckAt > lockAt, "the authoritative node re-read must happen inside the lock"); assert.ok(pushAt > lockAt, "the daemon push must run inside the lock (the pre-fix route pushed lock-free)"); assert.ok(persistAt > pushAt, "the persist must follow the successful push inside the same critical section"); assert.ok(!slice.includes("nodesRouter.rotateNodeToken("), "the route must not call the self-locking rotateNodeToken while holding the lock (non-reentrant deadlock)"); assert.ok(slice.includes("rotateNodeTokenPrelocked(fresh.id"), "the persist must go through the prelocked core"); const nodesSource = fs.readFileSync(NODES_JS, "utf8"); assert.ok(nodesSource.includes("module.exports.rotateNodeTokenPrelocked"), "nodes.js must export the prelocked persist core"); assert.ok( nodesSource.includes("MUST be called while\n// already holding withKeyedLock(`node-ports:`)"), "the prelocked core must document its caller-held-lock contract" ); }); test("source contract: the startup integrity gate call site injects the node row lock as withNodeLock", () => { // The gate's concurrency tests above inject their OWN wrapper, so only this // pin proves index.js actually passes withKeyedLock(`node-ports:`) — // dropping the injection would silently reopen the mid-startup applier race // the gate rotation test (b) closes. const source = fs.readFileSync(INDEX_JS, "utf8"); const start = source.indexOf("await verifyNodeTokenIntegrity({"); assert.ok(start >= 0, "the verifyNodeTokenIntegrity boot call site must exist"); const end = source.indexOf("Node token integrity check failed", start); assert.ok(end > start, "the gate call-site slice must be bounded by its catch handler"); const callSite = source.slice(start, end); assert.ok( callSite.includes("withNodeLock: (nodeId, task) => withKeyedLock(`node-ports:${nodeId}`, task)"), "the gate must inject withKeyedLock(`node-ports:`) as withNodeLock so each legacy-token swap serializes with the other full-row node writers" ); assert.ok( callSite.includes("getNodeByIdOrName: findNodeByIdOrName,"), "the gate must re-read the row inside the injected lock via findNodeByIdOrName" ); });