@davoodmehraban89 / LifeMate / commits / 43589da
Fork 0

LifeMate — Personal, Family & Learning Companion

fix(ops): require verified TLS in reachability smoke

Quinn White committed Oct 9, 2026 at 07:45 UTC 43589da9469ed78bdc503fc672be4acc2c08e6ba
2 files changed +160 -2
scripts/reachability-smoke.mjs
+4 -2
@@ -17,13 +17,14 @@ async function request(path, { method = 'GET', json, token } = {}) {
17 if (url.origin !== origin.origin) throw new Error('Cross-origin request refused');
18 const body = json === undefined ? undefined : JSON.stringify(json);
19 return await new Promise((resolve, reject) => {
20 - const req = https.request(url, { method, ca, timeout: 15000, headers: {
20 + const req = https.request(url, { method, ca, rejectUnauthorized: true, timeout: 15000, headers: {
21 ...(body ? { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) } : {}),
22 ...(token ? { Authorization: `Bearer ${token}` } : {}),
23 } }, res => {
24 + const tls = res.socket?.authorized;
25 const chunks = []; let size = 0;
26 res.on('data', chunk => { size += chunk.length; if (size > 4 * 1024 * 1024) req.destroy(new Error('Oversize response')); else chunks.push(chunk); });
26 - res.on('end', () => resolve({ status: res.statusCode, text: Buffer.concat(chunks).toString('utf8'), headers: res.headers, tls: res.socket?.authorized }));
27 + res.on('end', () => resolve({ status: res.statusCode, text: Buffer.concat(chunks).toString('utf8'), headers: res.headers, tls }));
28 });
29 req.on('timeout', () => req.destroy(new Error('Timeout')));
30 req.on('error', reject);
@@ -34,6 +35,7 @@ async function request(path, { method = 'GET', json, token } = {}) {
35 function assert(condition, message) { if (!condition) throw new Error(message); }
36 try {
37 const health = await request('/health');
38 + assert(health.tls === true, 'TLS certificate chain and hostname are not verified');
39 record('TLS', 'PASS', 'Certificate chain and hostname verified by Node TLS');
40 currentCheck = '/health';
41 assert(health.status === 200 && JSON.parse(health.text).status === 'ok', `health HTTP ${health.status}`);
scripts/test-reachability-smoke.mjs new
+156
@@ -0,0 +1,156 @@
1 +#!/usr/bin/env node
2 +// Real loopback HTTPS only. Temporary CA/private keys are removed after the suite.
3 +import assert from 'node:assert/strict';
4 +import { spawn, execFile } from 'node:child_process';
5 +import { promisify } from 'node:util';
6 +import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
7 +import https from 'node:https';
8 +import { tmpdir } from 'node:os';
9 +import { join } from 'node:path';
10 +import { fileURLToPath } from 'node:url';
11 +import { after, before, test } from 'node:test';
12 +
13 +const runFile = promisify(execFile);
14 +const smoke = fileURLToPath(new URL('./reachability-smoke.mjs', import.meta.url));
15 +let directory;
16 +let caFile;
17 +const certificates = {};
18 +
19 +before(async () => {
20 + directory = await mkdtemp(join(tmpdir(), 'lifeguide-smoke-tls-'));
21 + try {
22 + caFile = join(directory, 'ca.pem');
23 + const caKey = join(directory, 'ca-key.pem');
24 + await runFile('openssl', ['req', '-x509', '-newkey', 'rsa:2048', '-nodes', '-days', '1',
25 + '-keyout', caKey, '-out', caFile, '-subj', '/CN=LifeGuide local regression CA',
26 + '-addext', 'basicConstraints=critical,CA:TRUE']);
27 + for (const [name, san] of [['matching', 'IP:127.0.0.1'], ['mismatch', 'DNS:wrong.invalid']]) {
28 + const keyFile = join(directory, `${name}-key.pem`);
29 + const requestFile = join(directory, `${name}.csr`);
30 + const certFile = join(directory, `${name}.pem`);
31 + const extensionsFile = join(directory, `${name}.ext`);
32 + await writeFile(extensionsFile, `subjectAltName=${san}\nextendedKeyUsage=serverAuth\n`);
33 + await runFile('openssl', ['req', '-new', '-newkey', 'rsa:2048', '-nodes',
34 + '-keyout', keyFile, '-out', requestFile, '-subj', '/CN=LifeGuide loopback fixture']);
35 + await runFile('openssl', ['x509', '-req', '-in', requestFile, '-CA', caFile,
36 + '-CAkey', caKey, '-CAcreateserial', '-days', '1', '-out', certFile,
37 + '-extfile', extensionsFile]);
38 + certificates[name] = { key: await readFile(keyFile), cert: await readFile(certFile) };
39 + }
40 + } catch (error) {
41 + await rm(directory, { recursive: true, force: true });
42 + throw error;
43 + }
44 +});
45 +
46 +after(async () => {
47 + if (directory) await rm(directory, { recursive: true, force: true });
48 +});
49 +
50 +async function exercise({ certificate = 'matching', trustCa = false, disableTls = false, allowWrite = false } = {}) {
51 + const requests = [];
52 + const sockets = new Set();
53 + const server = https.createServer(certificates[certificate], (req, res) => {
54 + requests.push({ method: req.method, path: req.url, authorization: Boolean(req.headers.authorization) });
55 + res.setHeader('Content-Type', 'application/json');
56 + if (req.url === '/health') res.end(JSON.stringify({ status: 'ok' }));
57 + else if (req.url === '/') {
58 + res.setHeader('Content-Type', 'text/html');
59 + res.end('<!doctype html><title>LifeGuide local fixture</title>');
60 + } else if (req.url === '/manifest.json') res.end(JSON.stringify({ display: 'standalone' }));
61 + else if (req.url === '/config.json') {
62 + res.setHeader('Cache-Control', 'no-store');
63 + res.end(JSON.stringify({ apiBaseUrl: '/api' }));
64 + } else {
65 + res.statusCode = 401;
66 + res.end(JSON.stringify({ error: 'authentication_required' }));
67 + }
68 + });
69 + server.on('connection', socket => {
70 + sockets.add(socket);
71 + socket.on('close', () => sockets.delete(socket));
72 + });
73 + await new Promise((resolve, reject) => {
74 + server.once('error', reject);
75 + server.listen(0, '127.0.0.1', resolve);
76 + });
77 + try {
78 + const env = { PATH: process.env.PATH };
79 + if (trustCa) env.ROOT_CA_FILE = caFile;
80 + // Adversarial inherited setting: never used for the trusted acceptance case.
81 + if (disableTls) env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
82 + if (allowWrite) {
83 + env.SMOKE_ALLOW_SYNTHETIC_WRITE = 'yes';
84 + env.SMOKE_EMAIL = 'loopback-fixture@lifeguide.test';
85 + env.SMOKE_PASSWORD = 'local-synthetic-fixture-password';
86 + }
87 + const child = spawn(process.execPath, [smoke, `https://127.0.0.1:${server.address().port}`], {
88 + env, stdio: ['ignore', 'pipe', 'pipe'],
89 + });
90 + let stdout = '';
91 + let stderr = '';
92 + child.stdout.on('data', chunk => { stdout += chunk; });
93 + child.stderr.on('data', chunk => { stderr += chunk; });
94 + const timer = setTimeout(() => child.kill('SIGKILL'), 20000);
95 + let code;
96 + try {
97 + code = await new Promise((resolve, reject) => {
98 + child.once('error', reject);
99 + child.once('close', resolve);
100 + });
101 + } finally {
102 + clearTimeout(timer);
103 + }
104 + assert.notEqual(code, null, 'Loopback smoke timed out');
105 + return { code, report: JSON.parse(stdout), stderr, requests };
106 + } finally {
107 + for (const socket of sockets) socket.destroy();
108 + await new Promise(resolve => server.close(resolve));
109 + }
110 +}
111 +
112 +function assertTlsFailure(outcome) {
113 + assert.equal(outcome.code, 1, 'Unverified TLS must fail the smoke process');
114 + assert.equal(outcome.report.results.some(result => result.name === 'TLS' && result.status === 'PASS'), false,
115 + 'Unverified TLS must never be reported as PASS');
116 + assert.equal(outcome.report.results[0]?.status, 'FAIL');
117 + assert.equal(outcome.requests.some(request => request.authorization || request.method !== 'GET'
118 + || request.path.startsWith('/api/v1/auth/')), false, 'TLS failure must precede auth and writes');
119 +}
120 +
121 +test('trusted local CA and matching hostname pass read-only smoke without TLS-disable', async () => {
122 + const outcome = await exercise({ trustCa: true });
123 + assert.equal(outcome.code, 0);
124 + assert.equal(outcome.report.results.find(result => result.name === 'TLS')?.status, 'PASS');
125 + assert.equal(outcome.report.results.some(result => result.status === 'FAIL'), false);
126 + assert.equal(outcome.report.results.find(result => result.name === 'API round-trip')?.status, 'UNVERIFIED');
127 + assert.deepEqual(outcome.requests.map(request => request.path),
128 + ['/health', '/', '/manifest.json', '/config.json', '/api/v1/plan-items']);
129 + assert.equal(outcome.requests.some(request => request.authorization || request.method !== 'GET'), false);
130 + assert.equal(outcome.stderr, '');
131 +});
132 +
133 +test('untrusted CA fails before opted-in synthetic auth or writes', async () => {
134 + const outcome = await exercise({ allowWrite: true });
135 + assertTlsFailure(outcome);
136 + assert.equal(outcome.requests.length, 0);
137 +});
138 +
139 +test('inherited NODE_TLS_REJECT_UNAUTHORIZED=0 cannot produce a false TLS PASS', async t => {
140 + const outcome = await exercise({ disableTls: true });
141 + t.diagnostic(`Local untrusted fixture: exit=${outcome.code}, TLS=${outcome.report.results.find(result => result.name === 'TLS')?.status ?? 'not recorded'}`);
142 + assertTlsFailure(outcome);
143 + assert.equal(outcome.requests.length, 0);
144 +});
145 +
146 +test('inherited TLS-disable cannot reach opted-in synthetic auth or writes', async () => {
147 + const outcome = await exercise({ disableTls: true, allowWrite: true });
148 + assertTlsFailure(outcome);
149 + assert.equal(outcome.requests.length, 0);
150 +});
151 +
152 +test('trusted CA with hostname mismatch fails before opted-in synthetic auth or writes', async () => {
153 + const outcome = await exercise({ certificate: 'mismatch', trustCa: true, allowWrite: true });
154 + assertTlsFailure(outcome);
155 + assert.equal(outcome.requests.length, 0);
156 +});