// P2 RED: catch wrong-key preflight, 401 success, redirect following and unbounded probes. import test from 'node:test'; import assert from 'node:assert/strict'; import http from 'node:http'; import { ManagementClient } from '../src/client.mjs'; async function fixture(t, handler) { const server = http.createServer(handler); await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); t.after(() => new Promise(resolve => { server.closeAllConnections(); server.close(resolve); })); const baseUrl = `http://127.0.0.1:${server.address().port}`; const receipts = []; return { server, receipts, client: new ManagementClient({ baseUrl, key: 'fx331-manage', receipt: r => receipts.push(r) }) }; } for (const status of [200, 401, 503]) { test(`probeKey observes ${status} with one agent-authenticated GET /v1/models`, async t => { const calls = []; const f = await fixture(t, (req, res) => { calls.push({ path: req.url, method: req.method, ownKey: req.headers.authorization === 'Bearer fx331-agent' }); res.writeHead(status); res.end('fixture-body'); }); assert.equal(typeof f.client.probeKey, 'function', 'client must support bounded agent-key probe'); assert.equal(await f.client.probeKey('fx331-agent', { timeout: 100 }), status); assert.deepEqual(calls, [{ path: '/v1/models', method: 'GET', ownKey: true }]); const output = JSON.stringify(f.receipts); assert.equal(output.includes('fx331-agent'), false); assert.equal(output.includes('fx331-manage'), false); }); } test('proxy-down: agent-key probe connection failure is sanitized', async t => { const f = await fixture(t, (_req, res) => res.end()); await new Promise(resolve => f.server.close(resolve)); assert.equal(typeof f.client.probeKey, 'function'); await assert.rejects(f.client.probeKey('fx331-agent', { timeout: 100 }), e => e.code === 'proxy-down' && !e.message.includes('fx331-agent')); }); test('proxy-down: silent listener cannot extend probe request deadline', async t => { const f = await fixture(t, () => {}); assert.equal(typeof f.client.probeKey, 'function'); const started = performance.now(); await assert.rejects(f.client.probeKey('fx331-agent', { timeout: 50 }), e => e.code === 'proxy-down'); assert.ok(performance.now() - started < 1000, 'bounded HTTP probe must settle'); }); test('agent-key probe returns redirect status without following Location or exposing key', async t => { let calls = 0; const f = await fixture(t, (_req, res) => { calls++; res.writeHead(302, { Location: '/wrong' }); res.end(); }); assert.equal(typeof f.client.probeKey, 'function'); assert.equal(await f.client.probeKey('fx331-agent', { timeout: 100 }), 302); assert.equal(calls, 1); });