okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-0213-guidata (4c4596746) into f-0213-int22a3d7068

main
6.8 KiB112 linesraw
1import test from 'node:test';
2import assert from 'node:assert/strict';
3import { spawn } from 'node:child_process';
4import { mkdtemp, rm } from 'node:fs/promises';
5import { tmpdir } from 'node:os';
6import { join } from 'node:path';
7import net from 'node:net';
8import { fileURLToPath } from 'node:url';
9
10/**
11 * #4397: one request with an empty or malformed Host header (or a request target that is not a path) used to end the
12 * whole host: the URL was built before the routing try/catch, the async handler rejected, and Node ends the process on
13 * an unhandled rejection. A bad request now gets a bounded 400 and the host keeps serving.
14 */
15const root = fileURLToPath(new URL('..', import.meta.url));
16const delay = ms => new Promise(r => setTimeout(r, ms));
17async function freePort() { const s = net.createServer(); await new Promise(r => s.listen(0, '127.0.0.1', r)); const p = s.address().port; await new Promise(r => s.close(r)); return p; }
18
19async function startHost() {
20  const home = await mkdtemp(join(tmpdir(), 'strata-host-badhost-'));
21  const port = await freePort(), sharePort = await freePort();
22  const env = {
23    ...process.env, STRATA_HOME: home, STRATA_MODELS_DIR: join(home, 'models'), STRATA_PORT: String(port),
24    STRATA_SHARE_PORT: String(sharePort), STRATA_TUNNEL_PORT: String(await freePort()), STRATA_REAL_ENGINE: '1',
25    STRATA_SETTINGS_FILE: join(home, 'app-settings.json'), STRATA_COMPONENTS_DIR: join(home, 'components'),
26    LOCALAPPDATA: join(home, 'Local'), APPDATA: join(home, 'Roaming'), XDG_DATA_HOME: join(home, 'xdg-data'),
27    XDG_STATE_HOME: join(home, 'xdg-state'), XDG_CONFIG_HOME: join(home, 'xdg-config'),
28  };
29  const host = spawn(process.execPath, ['server/index.mjs'], { cwd: root, stdio: 'ignore', env });
30  const exit = new Promise(r => host.once('exit', (code, signal) => r({ code, signal })));
31  let up = false;
32  for (let i = 0; i < 150 && !up; i++) { try { up = (await fetch(`http://127.0.0.1:${port}/api/health`)).ok; } catch { await delay(100); } }
33  assert.ok(up, 'host started');
34  return { host, port, sharePort, exit, done: async () => { host.kill('SIGKILL'); await exit; await rm(home, { recursive: true, force: true }).catch(() => {}); } };
35}
36
37/** One raw HTTP request on its own socket: the bytes are sent as written and the first response is returned. */
38function raw(port, bytes) {
39  return new Promise((resolve, reject) => {
40    const socket = net.connect(port, '127.0.0.1');
41    let data = '';
42    const finish = () => { socket.destroy(); resolve(data); };
43    const timer = setTimeout(finish, 4000);
44    socket.on('connect', () => socket.write(bytes));
45    socket.on('data', chunk => { data += chunk; if (/\r\n\r\n/.test(data) && /content-length: *\d+/i.test(data)) { const body = data.split('\r\n\r\n')[1] ?? ''; const len = Number(/content-length: *(\d+)/i.exec(data)[1]); if (Buffer.byteLength(body) >= len) { clearTimeout(timer); finish(); } } });
46    socket.on('close', () => { clearTimeout(timer); resolve(data); });
47    socket.on('error', e => { clearTimeout(timer); data ? resolve(data) : reject(e); });
48  });
49}
50const status = response => Number(/^HTTP\/1\.[01] (\d{3})/.exec(response)?.[1] ?? 0);
51
52test('requestUrl: a good Host (name, port, IPv6) or none gives the URL; an empty or malformed Host or target gives null', async () => {
53  const { requestUrl } = await import('../server/util.mjs');
54  const req = (url, host) => ({ url, headers: host === undefined ? {} : { host } });
55  assert.equal(requestUrl(req('/api/health?x=1', 'localhost:8791')).pathname, '/api/health');
56  assert.equal(requestUrl(req('/api/health?x=1', 'localhost:8791')).searchParams.get('x'), '1');
57  assert.equal(requestUrl(req('/', '[::1]:8791')).pathname, '/');
58  assert.equal(requestUrl(req('/', '127.0.0.1')).pathname, '/');
59  assert.equal(requestUrl(req('/')).pathname, '/', 'no Host (HTTP/1.0) is read as localhost');
60  assert.equal(requestUrl({ headers: {} }).pathname, '/', 'no url at all is the root');
61  for (const bad of ['', ' ', 'a b', 'exa mple.com', 'a/b', 'a?b', 'a#b', 'u@h', 'h\\x', '[::1', 'http://x', '%zz', 'a:99999']) {
62    assert.equal(requestUrl(req('/', bad)), null, `Host ${JSON.stringify(bad)}`);
63  }
64  assert.equal(requestUrl(req('//', 'localhost')), null, 'a target of // has no host to read');
65  assert.equal(requestUrl(req('http://', 'localhost')), null);
66});
67
68test('App Host: an empty, missing, malformed or IPv6 Host never ends the process; a healthy request on another socket still works', async t => {
69  const h = await startHost();
70  t.after(h.done);
71  let ended = null;
72  h.exit.then(r => { ended = r; });
73
74  const empty = await raw(h.port, 'GET /api/health HTTP/1.1\r\nHost: \r\nConnection: close\r\n\r\n');
75  assert.equal(status(empty), 400, `empty Host: ${empty.slice(0, 80)}`);
76  assert.match(empty, /bad_host/);
77  assert.equal(ended, null, 'the host survived an empty Host');
78  const alive = await fetch(`http://127.0.0.1:${h.port}/api/health`);
79  assert.equal(alive.status, 200, 'a healthy request on a separate socket after the empty Host');
80
81  const spaced = await raw(h.port, 'GET /api/health HTTP/1.1\r\nHost: a b\r\nConnection: close\r\n\r\n');
82  assert.equal(status(spaced), 400, 'malformed Host');
83  assert.ok(spaced.length < 1000, 'the 400 is bounded');
84  for (const odd of ['a/b', 'u@h', '[::1', 'x y z', '%zz']) {
85    const r = await raw(h.port, `GET /api/health HTTP/1.1\r\nHost: ${odd}\r\nConnection: close\r\n\r\n`);
86    assert.equal(status(r), 400, `Host ${odd}`);
87  }
88  assert.equal(ended, null, 'the host survived the malformed Hosts');
89
90  const none = await raw(h.port, 'GET /api/health HTTP/1.0\r\n\r\n');
91  assert.equal(status(none), 200, 'HTTP/1.0 without a Host is served');
92
93  const ipv6 = await raw(h.port, `GET /api/health HTTP/1.1\r\nHost: [::1]:${h.port}\r\nConnection: close\r\n\r\n`);
94  assert.equal(status(ipv6), 200, 'a valid IPv6 Host is served');
95
96  const target = await raw(h.port, 'GET // HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n');
97  assert.equal(status(target), 400, 'a request target that is not a path');
98
99  assert.equal(ended, null, 'the host is still running');
100  assert.equal((await fetch(`http://127.0.0.1:${h.port}/api/health`)).status, 200, 'and still answers');
101});
102
103test('The share listener also survives a request target that is not a path', async t => {
104  const h = await startHost();
105  t.after(h.done);
106  // the share listener is off until sharing is started: start it the way the app does
107  const started = await fetch(`http://127.0.0.1:${h.port}/api/serving/share`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ enabled: true }) }).catch(() => null);
108  if (!started || !started.ok) return t.skip('could not start the share listener in this environment');
109  const bad = await raw(h.sharePort, 'GET // HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n');
110  assert.equal(status(bad), 400);
111  assert.equal((await fetch(`http://127.0.0.1:${h.port}/api/health`)).status, 200);
112});