From dbd92f98df09de34462d4d0f67045ef71f1f22bd Mon Sep 17 00:00:00 2001 From: tesseractAZ <192581158+tesseractAZ@users.noreply.github.com> Date: Fri, 27 Nov 2026 10:59:47 -0700 Subject: [PATCH] Tests: free ports for the SSH server tests; the closing-socket test reruns a trial that missed its order; README: AppArmor compile is a required check Co-Authored-By: Claude Opus 5.5 --- README.md | 5 +- .../test/haWsClientLateSubscribe.test.ts | 81 +++++++++++-------- zwave_tui/server/test/ingressTrust.test.ts | 56 +++++++++---- 3 files changed, 90 insertions(+), 52 deletions(-) diff --git a/README.md b/README.md index 32702c8..172f725 100644 --- a/README.md +++ b/README.md @@ -591,9 +591,8 @@ releasing anything — docs and tooling changes ride along until the next releas plus an AppArmor-profile compile) and `codeql.yml` (CodeQL `security-extended`; results are uploaded to the Security tab, and `check-sarif.mjs` fails the job on actionable findings) run on every PR to `main`, and every job of both is a -required status check except the AppArmor compile, which is not yet in that -set. Every job, CodeQL included, runs on a pinned `ubuntu-26.04` image (native -`ubuntu-26.04-arm` for aarch64 builds). +required status check. Every job, CodeQL included, runs on a pinned +`ubuntu-26.04` image (native `ubuntu-26.04-arm` for aarch64 builds). ## Local development diff --git a/zwave_tui/server/test/haWsClientLateSubscribe.test.ts b/zwave_tui/server/test/haWsClientLateSubscribe.test.ts index 924c726..4df4c75 100644 --- a/zwave_tui/server/test/haWsClientLateSubscribe.test.ts +++ b/zwave_tui/server/test/haWsClientLateSubscribe.test.ts @@ -350,41 +350,52 @@ test('the release leaves in the same turn as the timeout: ahead of anything the }); test('a reply bound that passes while the socket is closing (terminated, its close event not yet run) sends no release, on that socket or the next (v0.79.7)', async () => { - const h = await core(); - const never = new Promise(() => {}); - h.plan = (_ci, m) => (m.type === 'subscribe_events' ? { hold: never } : null); - const c = client(h.url); - const cpriv = c as unknown as { ws: { readyState: number } | null; pending: Map }; - const u = unhandled(); - try { - c.start(); - await waitFor(() => c.ready()); - // Two timers of one duration set in one turn run in one pass of the timers - // phase, in the order set: the terminate first, then the subscribe's reply - // bound, before the socket's close callback can run (libuv's close phase). - let stateAtTimeout = -1; - setTimeout(() => { c.reconnect(); stateAtTimeout = cpriv.ws?.readyState ?? -1; }, 120); - await assert.rejects(c.subscribe({ type: 'subscribe_events', event_type: 'state_changed' }, () => {}, 120), /^Error: HA WS timeout/, - 'the reply bound ran before the close event: the gap was reached'); - assert.equal(stateAtTimeout, 2, 'precondition: the socket was CLOSING when the bound passed'); - await waitFor(() => h.conns.length === 2 && c.ready(), 8000, 'reconnected'); - const c1 = h.conns[1]; - await c.send({ type: 'ping-ish' }, 2000); - await sleep(50); - assert.deepEqual(releasesSent(h.conns[0]), [], 'nothing went out on the closing socket'); - assert.deepEqual(releasesSent(c1), [], 'and nothing on the next one'); - assert.equal(cpriv.pending.size, 0); - // The control: on an open socket, a subscribe given up on is released. - await assert.rejects(c.subscribe({ type: 'subscribe_events', event_type: 'state_changed' }, () => {}, 80), /HA WS timeout/); - const s1 = subscribes(c1)[0].id as number; - await waitFor(() => releasesSent(c1).length === 1, 2000, 'released on the open socket'); - assert.equal(releasesSent(c1)[0].subscription, s1); - assert.deepEqual(h.idReuse, []); - assert.deepEqual(u.seen, []); - } finally { - u.off(); - c.stop(); - await h.close(); + // Two timers of one duration set in one turn run in one pass of the timers + // phase, in the order set: the terminate first, then the subscribe's reply + // bound, before the socket's close callback can run (libuv's close phase). + // On a loaded machine the close event can still run between them; that + // trial rejects with the connection closed and never reached the order this + // test is about, so it is run again. A trial that reaches it is judged in + // full. + for (let attempt = 1; ; attempt++) { + const h = await core(); + const never = new Promise(() => {}); + h.plan = (_ci, m) => (m.type === 'subscribe_events' ? { hold: never } : null); + const c = client(h.url); + const cpriv = c as unknown as { ws: { readyState: number } | null; pending: Map }; + const u = unhandled(); + try { + c.start(); + await waitFor(() => c.ready()); + let stateAtTimeout = -1; + setTimeout(() => { c.reconnect(); stateAtTimeout = cpriv.ws?.readyState ?? -1; }, 120); + const err = await c.subscribe({ type: 'subscribe_events', event_type: 'state_changed' }, () => {}, 120) + .then(() => null, (e: unknown) => e); + if (!(/^Error: HA WS timeout/.test(String(err)) && stateAtTimeout === 2)) { + assert.ok(attempt < 5, + `the reply bound never passed while the socket was CLOSING in 5 trials (last: ${String(err)}, state ${stateAtTimeout})`); + continue; + } + await waitFor(() => h.conns.length === 2 && c.ready(), 8000, 'reconnected'); + const c1 = h.conns[1]; + await c.send({ type: 'ping-ish' }, 2000); + await sleep(50); + assert.deepEqual(releasesSent(h.conns[0]), [], 'nothing went out on the closing socket'); + assert.deepEqual(releasesSent(c1), [], 'and nothing on the next one'); + assert.equal(cpriv.pending.size, 0); + // The control: on an open socket, a subscribe given up on is released. + await assert.rejects(c.subscribe({ type: 'subscribe_events', event_type: 'state_changed' }, () => {}, 80), /HA WS timeout/); + const s1 = subscribes(c1)[0].id as number; + await waitFor(() => releasesSent(c1).length === 1, 2000, 'released on the open socket'); + assert.equal(releasesSent(c1)[0].subscription, s1); + assert.deepEqual(h.idReuse, []); + assert.deepEqual(u.seen, []); + return; + } finally { + u.off(); + c.stop(); + await h.close(); + } } }); diff --git a/zwave_tui/server/test/ingressTrust.test.ts b/zwave_tui/server/test/ingressTrust.test.ts index 730a5de..a42b6dd 100644 --- a/zwave_tui/server/test/ingressTrust.test.ts +++ b/zwave_tui/server/test/ingressTrust.test.ts @@ -31,7 +31,23 @@ const TEST_HOST_KEY = generateHostKey().key; import { mkNode, mockData } from './_logHelpers'; /** Fixed high port for the telnet cap probe (0 gives no discoverable port). */ -const TELNET_TEST_PORT = 24391; +/** A free loopback port for one test's server. A fixed port collided when + * two suites ran at once on one machine (a mutation run beside a review's + * suite): one server could not bind, and its client reached the other + * process's server, which never logged its accept and closed under it. The + * port is released before the server binds it; nothing else on loopback + * takes it in between. */ +async function freePort(): Promise { + const { createServer } = await import('node:net'); + return new Promise((resolve, reject) => { + const s = createServer(); + s.once('error', reject); + s.listen(0, '127.0.0.1', () => { + const { port } = s.address() as import('node:net').AddressInfo; + s.close(() => resolve(port)); + }); + }); +} /** The composition used in index.ts — kept verbatim so this tests the real rule. */ const isIngressTrusted = (req: { headers: Record; ip: string }): boolean => @@ -250,23 +266,22 @@ test('one host cannot take every SSH slot', async () => { const { startSshServer } = await import('../src/telnet/server'); const { connect } = await import('node:net'); + const port = await freePort(); const srv = startSshServer({ hostKey: TEST_HOST_KEY, data: mockData({ nodes: [mkNode()] }), host: '127.0.0.1', - port: TELNET_TEST_PORT, + port, log: () => {}, signalDisplay: 'margin', } as never); - // startTelnetServer does not surface the bound port, so probe the fixed one - // only when it is actually listening; otherwise assert the rule directly. const results: string[] = []; await new Promise((done) => { let settled = 0; const N = 6; for (let i = 0; i < N; i++) { - const s = connect({ host: '127.0.0.1', port: TELNET_TEST_PORT }); + const s = connect({ host: '127.0.0.1', port }); let got = ''; s.setEncoding('utf8'); s.on('data', (d) => { got += d; }); @@ -306,18 +321,19 @@ test('a silent socket is reclaimed by the idle timeout', async () => { const { connect } = await import('node:net'); const logs: string[] = []; + const port = await freePort(); const srv = startSshServer({ hostKey: TEST_HOST_KEY, data: mockData({ nodes: [mkNode()] }), host: '127.0.0.1', - port: TELNET_TEST_PORT + 1, + port, log: (m: string) => { logs.push(m); }, signalDisplay: 'margin', idleTimeoutMs: 250, } as never); const closedWithin = await new Promise((done) => { - const s = connect({ host: '127.0.0.1', port: TELNET_TEST_PORT + 1 }); + const s = connect({ host: '127.0.0.1', port }); const timer = setTimeout(() => { s.destroy(); done(false); }, 3000); // Send nothing at all — this is the abusive case. But DO read: a socket // with no 'data' listener stays paused, so the server's FIN is never @@ -352,20 +368,31 @@ test('accepted sockets get TCP keepalive, to catch half-open peers', async () => } as typeof original; try { + // Hang up once the server has accepted the socket, not after a fixed + // delay: under a loaded event loop the accept handler could run after a + // 250 ms hang-up, and the test failed with no call seen. The accept + // handler logs "client connected" right after it sets keepalive, in the + // same synchronous step; the deadline only bounds a server that never + // accepts, which then fails the assertion below. + let accepted!: () => void; + const acceptedP = new Promise((resolve) => { accepted = resolve; }); + const port = await freePort(); const srv = startSshServer({ hostKey: TEST_HOST_KEY, data: mockData({ nodes: [mkNode()] }), host: '127.0.0.1', - port: TELNET_TEST_PORT + 2, - log: () => {}, + port, + log: (m: string) => { if (String(m).startsWith('ssh: client connected')) accepted(); }, signalDisplay: 'margin', keepAliveMs: 12_345, } as never); await new Promise((done) => { - const s = net.connect({ host: '127.0.0.1', port: TELNET_TEST_PORT + 2 }); - s.on('connect', () => setTimeout(() => { s.destroy(); done(); }, 250)); - s.on('error', () => done()); + const s = net.connect({ host: '127.0.0.1', port }); + const finish = () => { clearTimeout(deadline); s.destroy(); done(); }; + const deadline = setTimeout(finish, 10_000); + void acceptedP.then(finish); + s.on('error', finish); }); srv.stop(); } finally { @@ -430,18 +457,19 @@ test('an ACTIVE operator is never evicted by the idle sweep', async () => { const { startSshServer } = await import('../src/telnet/server'); const { connect } = await import('node:net'); + const port = await freePort(); const srv = startSshServer({ hostKey: TEST_HOST_KEY, data: mockData({ nodes: [mkNode()] }), host: '127.0.0.1', - port: TELNET_TEST_PORT + 3, + port, log: () => {}, signalDisplay: 'margin', idleTimeoutMs: 300, } as never); const survived = await new Promise((done) => { - const s = connect({ host: '127.0.0.1', port: TELNET_TEST_PORT + 3 }); + const s = connect({ host: '127.0.0.1', port }); s.resume(); // Type something harmless well inside every sweep window. const typing = setInterval(() => { if (!s.destroyed) s.write(' '); }, 80);