Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
81 changes: 46 additions & 35 deletions zwave_tui/server/test/haWsClientLateSubscribe.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void>(() => {});
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<number, unknown> };
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<void>(() => {});
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<number, unknown> };
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();
}
}
});

Expand Down
56 changes: 42 additions & 14 deletions zwave_tui/server/test/ingressTrust.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<number> {
const { createServer } = await import('node:net');
return new Promise<number>((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<string, unknown>; ip: string }): boolean =>
Expand Down Expand Up @@ -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<void>((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; });
Expand Down Expand Up @@ -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<boolean>((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
Expand Down Expand Up @@ -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<void>((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<void>((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 {
Expand Down Expand Up @@ -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<boolean>((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);
Expand Down