AtlatestRepositorysigil-http3

sigil-http3 / tree / scriptsecho-lifecycle.mjs

1// Prepared lifecycle tooling. Running a real server is a deployment and needs
2// Validates explicit host and resource limits before starting one child.
3import { spawn } from 'node:child_process';
4import { createHash, X509Certificate } from 'node:crypto';
5import { constants, accessSync, closeSync, lstatSync, mkdirSync, openSync,
6 readFileSync, renameSync, statSync, writeFileSync, writeSync } from 'node:fs';
7import { isIP } from 'node:net';
8import { hostname } from 'node:os';
9import { isAbsolute, join, resolve } from 'node:path';
10import { fileURLToPath } from 'node:url';
12const pause = ms => new Promise(done => setTimeout(done, ms));
13const sha256 = bytes => createHash('sha256').update(bytes).digest('hex');
14function check(value, message) { if (!value) throw new Error(message); }
15function boundedJson(path, maximum = 65536) {
16 check(statSync(path).size <= maximum, `JSON exceeds limit: ${path}`);
17 return JSON.parse(readFileSync(path, 'utf8'));
19export function identity(pid) {
20 if (!Number.isInteger(pid) || pid < 1) return null;
21 try {
22 const text = readFileSync(`/proc/${pid}/stat`, 'utf8');
23 const fields = text.slice(text.lastIndexOf(') ') + 2).split(' ');
24 return { pid, start: fields[19], uid: statSync(`/proc/${pid}`).uid, state: fields[0] };
25 } catch (error) { if (error.code === 'ENOENT' || error.code === 'ESRCH') return null; throw error; }
27export function sameIdentity(expected, actual) {
28 return !!expected && !!actual && expected.pid === actual.pid && expected.start === actual.start &&
29 expected.uid === actual.uid;
31function signalIdentity(expected, signal) {
32 const current = identity(expected?.pid);
33 if (!current || current.state === 'Z') return false;
34 check(sameIdentity(expected, current), `Refusing reused PID ${expected?.pid}`);
35 try { process.kill(expected.pid, signal); return true; }
36 catch (error) { if (error.code === 'ESRCH') return false; throw error; }
39export function inspectPlan(configPath) {
40 const config = boundedJson(configPath);
41 check(config.schema === 1 && /^[a-z0-9][a-z0-9-]{0,63}$/.test(config.testId), 'Invalid lifecycle schema/testId');
42 check(config.expectedHost === hostname(), 'Configured host does not match this machine');
43 for (const name of ['binary', 'certificateDirectory', 'runDirectory', 'interopReceipt']) {
44 check(typeof config[name] === 'string' && isAbsolute(config[name]), `${name} must be an absolute path`);
45 }
46 const family = isIP(config.bindAddress);
47 check(family !== 0, 'Choose an explicit numeric bind address');
48 const scope = config.scope ?? 'test-loopback';
49 check((scope === 'test-loopback' && ['127.0.0.1', '::1'].includes(config.bindAddress)) ||
50 (scope === 'vpn' && config.bindAddress === (process.env.HTTP3_IPV4_ADDRESS ?? '127.0.0.1')) ||
51 (scope === 'ipv6-direct' && family === 6 && /^[23][0-9a-f]{0,3}:/i.test(config.bindAddress) &&
52 !config.bindAddress.includes('%')), 'Bind address exceeds the configured run scope');
53 check(Number.isInteger(config.port) && config.port >= 1024 && config.port <= 65535, 'Choose an unprivileged UDP port');
54 check(Number.isInteger(config.lifetimeSeconds) && config.lifetimeSeconds >= 1 && config.lifetimeSeconds <= 7200,
55 'Test lifetime must be between 1 and 7200 seconds');
56 const authority = new URL(`https://${config.authority}`);
57 check(authority.host === config.authority && authority.pathname === '/' && !authority.search && !authority.hash &&
58 !authority.username && !authority.password, 'Invalid exact echo authority');
59 const expectedAuthority = family === 6 ? `[${config.bindAddress}]:${config.port}` : `${config.bindAddress}:${config.port}`;
60 check(authority.href === new URL(`https://${expectedAuthority}`).href, 'Echo authority must name the admitted bind and port');
61 check(Array.isArray(config.origins) && config.origins.length === 1 &&
62 config.origins.every(origin => {
63 if (origin === 'null') return true; // Explicit local-file page policy.
64 const url = new URL(origin);
65 return origin.length <= 512 && url.origin === origin && (url.protocol === 'https:' ||
66 (url.protocol === 'http:' && ['127.0.0.1', 'localhost'].includes(url.hostname)));
67 }), 'Choose exact secure page origins');
68 const binary = statSync(config.binary);
69 check(binary.isFile() && binary.size > 0 && binary.size <= 67108864, 'Invalid server binary size/type');
70 accessSync(config.binary, constants.X_OK);
71 const binarySha256 = sha256(readFileSync(config.binary));
72 check(binarySha256 === config.binarySha256, 'Server binary SHA-256 mismatch');
73 const certificatePath = join(config.certificateDirectory, 'cert.der');
74 check(statSync(certificatePath).size <= 65536, 'Certificate exceeds limit');
75 const certificate = new X509Certificate(readFileSync(certificatePath));
76 const validFrom = Date.parse(certificate.validFrom);
77 const validTo = Date.parse(certificate.validTo);
78 check(certificate.publicKey.asymmetricKeyType === 'ec' &&
79 ['prime256v1', 'P-256'].includes(certificate.publicKey.asymmetricKeyDetails?.namedCurve), 'Certificate must be ECDSA P-256');
80 check(validFrom <= Date.now() && validTo >= Date.now() + config.lifetimeSeconds * 1000 &&
81 validTo - validFrom <= 14 * 86400000, 'Certificate must cover the test and be valid at most 14 days');
82 const privateKey = lstatSync(join(config.certificateDirectory, 'private.raw'));
83 check(privateKey.isFile() && privateKey.size === 32 && (privateKey.mode & 0o077) === 0 &&
84 privateKey.uid === process.getuid(), 'Raw signing key must be private, owned and exactly 32 bytes');
85 const certificateSha256 = sha256(certificate.raw);
86 const blockers = [];
87 let receipt;
88 try { receipt = boundedJson(config.interopReceipt); }
89 catch (error) { blockers.push(`Real echo receipt unavailable: ${error.message}`); }
90 if (receipt) {
91 if (receipt.mode !== 'webtransport-echo') blockers.push('A capability preflight is not a real WebTransport echo receipt');
92 if (!['ready', 'bidirectionalEcho', 'unidirectionalEcho', 'datagramEcho', 'chromeReaped', 'serverReaped']
93 .every(name => receipt[name] === true)) blockers.push('Real browser echo and process cleanup have not all passed');
94 const required = ['configurableBind', 'retry', 'antiAmplification', 'peerAddressLogging', 'pathChangeLogging',
95 'cidChangeLogging', 'boundedAdmission', 'echoOnly'];
96 const missing = required.filter(name => receipt.server?.[name] !== true);
97 if (missing.length) blockers.push(`Server prerequisites missing: ${missing.join(', ')}`);
98 if (receipt.binarySha256 !== binarySha256 || receipt.certificateSha256 !== certificateSha256)
99 blockers.push('Interop receipt must cover this exact binary and certificate');
100 if (!/^[0-9a-f]{40}$/.test(receipt.sourceRevision ?? '') || !/^[0-9a-f]{40}$/.test(receipt.quicRevision ?? '') ||
101 typeof receipt.browser !== 'string' || !receipt.browser || typeof receipt.profile !== 'string' || !receipt.profile)
102 blockers.push('Interop receipt needs source/QUIC revisions, browser and measured profile');
103 }
104 try { lstatSync(config.runDirectory); blockers.push('Run directory already exists; preserve it and choose a fresh one'); }
105 catch (error) { if (error.code !== 'ENOENT') throw error; }
106 return { config, ready: blockers.length === 0, blockers, binarySha256, certificateSha256 };
109function writeState(directory, state) {
110 const temporary = join(directory, 'state.next');
111 writeFileSync(temporary, JSON.stringify(state, null, 2) + '\n', { mode: 0o600, flag: 'w' });
112 renameSync(temporary, join(directory, 'state.json'));
114function ownedDirectory(directory) {
115 const info = lstatSync(directory);
116 check(info.isDirectory() && info.uid === process.getuid() && (info.mode & 0o077) === 0,
117 'Run directory must be private and owned by this user');
119export function stopRun(directory) {
120 ownedDirectory(directory);
121 const info = lstatSync(join(directory, 'state.json'));
122 check(info.isFile() && info.uid === process.getuid() && (info.mode & 0o077) === 0, 'Invalid owned state receipt');
123 const state = boundedJson(join(directory, 'state.json'));
124 check(state.schema === 1 && state.supervisor?.uid === process.getuid(), 'Invalid supervisor admission receipt');
125 if (state.phase === 'finished') return { stopped: true, alreadyFinished: true, childReaped: state.childReaped };
126 return { stopRequested: signalIdentity(state.supervisor, 'SIGTERM') };
129export async function runTest(configPath, { signal } = {}) {
130 const plan = inspectPlan(configPath);
131 check(plan.ready, plan.blockers.join('; '));
132 const { config } = plan;
133 mkdirSync(config.runDirectory, { mode: 0o700 }); // Exclusive; never clobber another run.
134 ownedDirectory(config.runDirectory);
135 const state = { schema: 1, testId: config.testId, phase: 'starting', supervisor: identity(process.pid),
136 startedAt: new Date().toISOString(), bindAddress: config.bindAddress, port: config.port,
137 expiresAt: new Date(Date.now() + config.lifetimeSeconds * 1000).toISOString(),
138 binarySha256: plan.binarySha256, certificateSha256: plan.certificateSha256 };
139 let child;
140 let closed = false;
141 let code;
142 let childError;
143 let reason;
144 let failure;
145 let done = Promise.resolve();
146 const files = [];
147 const streams = [];
148 const terminate = () => { reason ??= 'SIGTERM'; };
149 const interrupt = () => { reason ??= 'SIGINT'; };
150 const cancel = () => { reason ??= 'parent-stop'; };
151 process.on('SIGTERM', terminate);
152 process.on('SIGINT', interrupt);
153 signal?.addEventListener('abort', cancel, { once: true });
154 if (signal?.aborted) cancel();
155 const timer = setTimeout(() => { reason ??= 'lifetime'; }, config.lifetimeSeconds * 1000);
156 try {
157 writeState(config.runDirectory, state);
158 const readyPath = join(config.runDirectory, 'ready.json');
159 child = spawn(config.binary, [], { cwd: config.runDirectory, shell: false, env: { ...process.env,
160 HTTP3_TEST_ID: config.testId, HTTP3_BIND_ADDRESS: config.bindAddress, HTTP3_PORT: String(config.port),
161 HTTP3_LIFETIME_SECONDS: String(config.lifetimeSeconds), HTTP3_CERTIFICATE_DIR: config.certificateDirectory,
162 HTTP3_AUTHORITY: config.authority, HTTP3_ORIGINS: JSON.stringify(config.origins), HTTP3_ORIGIN: config.origins[0],
163 HTTP3_CERTIFICATE_SHA256: plan.certificateSha256, HTTP3_READY_FILE: readyPath },
164 stdio: ['ignore', 'pipe', 'pipe'] });
165 done = new Promise(resolveDone => {
166 child.once('error', error => { childError = error; });
167 child.once('close', value => { closed = true; code = value; resolveDone(); });
168 });
169 state.child = identity(child.pid);
170 check(state.child && state.child.uid === process.getuid(), 'Could not admit owned server PID');
171 writeState(config.runDirectory, state);
172 for (const [name, stream] of [['stdout.log', child.stdout], ['stderr.log', child.stderr]]) {
173 const file = openSync(join(config.runDirectory, name), 'wx', 0o600);
174 files.push(file);
175 streams.push(stream);
176 let size = 0;
177 stream.on('data', bytes => {
178 const allowed = Math.max(0, Math.min(bytes.length, 8388608 - size));
179 try {
180 for (let offset = 0; offset < allowed;)
181 offset += writeSync(file, bytes, offset, allowed - offset);
182 } catch (error) { failure ??= error; reason ??= 'log-error'; }
183 size += bytes.length;
184 if (size > 8388608) { failure ??= new Error('Server log budget exceeded'); reason ??= 'log-limit'; }
185 });
186 }
187 const readyDeadline = Date.now() + 10000;
188 while (!closed && !reason) {
189 if (state.phase === 'starting') {
190 let ready;
191 try { ready = boundedJson(readyPath, 4096); }
192 catch (error) { if (error.code !== 'ENOENT') throw error; }
193 if (ready) {
194 check(ready.testId === config.testId && ready.bindAddress === config.bindAddress &&
195 ready.port === config.port && ready.certificateSha256 === plan.certificateSha256 &&
196 ready.retry === true && ready.antiAmplification === true, 'Server readiness contract mismatch');
197 state.phase = 'ready';
198 state.readyAt = new Date().toISOString();
199 writeState(config.runDirectory, state);
200 console.log(`RESULT lifecycle-ready test=${config.testId} address=${config.bindAddress} port=${config.port}`);
201 } else if (Date.now() >= readyDeadline) throw new Error('Server readiness deadline');
202 }
203 await Promise.race([done, pause(50)]);
204 }
205 if (childError) throw childError;
206 if (closed && code !== 0 && !reason) throw new Error(`Server exited with ${code}`);
207 check(state.phase === 'ready', 'Server stopped before matching readiness');
208 } catch (error) { failure ??= error; reason ??= 'failure'; }
209 finally {
210 clearTimeout(timer);
211 try {
212 if (child && !closed) {
213 signalIdentity(state.child, 'SIGTERM');
214 if (!await Promise.race([done.then(() => true), pause(2000).then(() => false)]))
215 signalIdentity(state.child, 'SIGKILL');
216 if (!await Promise.race([done.then(() => true), pause(2000).then(() => false)]))
217 throw new Error('Owned server child was not reaped');
218 }
219 } catch (error) { failure ??= error; }
220 process.off('SIGTERM', terminate);
221 process.off('SIGINT', interrupt);
222 signal?.removeEventListener('abort', cancel);
223 for (const stream of streams) { stream.removeAllListeners('data'); stream.destroy(); }
224 for (const file of files) closeSync(file);
225 Object.assign(state, { phase: 'finished', endedAt: new Date().toISOString(),
226 reason: reason ?? 'server-exit', childReaped: closed, code, error: failure?.message });
227 writeState(config.runDirectory, state);
228 }
229 if (failure) throw failure;
230 check(closed, 'Server child was not reaped');
231 console.log(`RESULT lifecycle-finished test=${config.testId} reason=${state.reason} child-reaped=${closed}`);
232 return state;
235if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
236 const [command, path] = process.argv.slice(2);
237 try {
238 check(['plan', 'run', 'stop'].includes(command) && path && process.argv.length === 4,
239 'Usage: node scripts/echo-lifecycle.mjs plan|run CONFIG.json | stop RUN_DIRECTORY');
240 if (command === 'plan') {
241 const plan = inspectPlan(resolve(path));
242 console.log(JSON.stringify(plan, null, 2));
243 if (!plan.ready) process.exitCode = 2;
244 } else if (command === 'stop') console.log(JSON.stringify(stopRun(resolve(path))));
245 else await runTest(resolve(path));
246 } catch (error) { console.error(`RESULT lifecycle-error ${error.message}`); process.exitCode = 1; }