import test from 'node:test'; import assert from 'node:assert/strict'; import { checkTls, discoverFinalHost } from '../src/checks/tls.mjs'; import { NetGuardError } from '../src/lib/net-guard.mjs'; // The TLS check now asks two questions: what certificate the typed host serves, and what // certificate the host a browser is redirected to serves. These tests drive both with injected // stubs — no resolver, no socket, no clock dependence (dates are relative to real now). const DAY = 86_400_000; const daysFromNow = (days) => new Date(Date.now() + days * DAY).toISOString(); function tlsInfo(host, { san = `DNS:${host}`, validTo = daysFromNow(120), authorized = true, includeIntermediate = true } = {}) { const subject = { CN: host }; const issuer = { CN: 'R3', O: "Let's Encrypt" }; const leaf = { subject, issuer, validFrom: daysFromNow(-30), validTo, signatureAlgorithm: 'sha256WithRSAEncryption', fingerprint256: `FP-${host}`, selfSigned: false }; const intermediate = { subject: issuer, issuer: { CN: 'ISRG Root X1' }, validFrom: daysFromNow(-300), validTo: daysFromNow(900), signatureAlgorithm: 'sha256WithRSAEncryption', fingerprint256: `FP-INT-${host}`, selfSigned: false }; const chain = [leaf, intermediate]; const cert = { ...leaf, subjectAltName: san, authorized, authorizationError: null, protocol: 'TLSv1.3', chain }; return { host, port: 443, address: '93.184.216.34', cipher: { name: 'TLS_AES_256_GCM_SHA384' }, cert, chain: includeIntermediate ? chain : [leaf] }; } /** Routes by hostname; a handler may throw a NetGuardError to model a failed hop. */ function fakeRequest(byHost) { const calls = []; const fn = async (url, options = {}) => { calls.push({ url, method: options.method || 'GET' }); const host = new URL(url).hostname; const handler = byHost[host]; if (!handler) throw new Error(`unexpected request to ${url}`); const res = typeof handler === 'function' ? handler(options, url) : handler; return { url, status: 200, headers: {}, body: '', timing: { totalMs: 1 }, tls: null, ...res }; }; fn.calls = calls; return fn; } /** Returns fixture info per host; a NetGuardError value means the handshake failed. */ function fakeInspect(byHost) { const calls = []; const fn = async (host) => { calls.push(host); const value = byHost[host]; if (value === undefined) throw new Error(`unexpected inspect of ${host}`); if (value instanceof Error) throw value; return value; }; fn.calls = calls; return fn; } function codes(result) { return result.findings.map((finding) => finding.code); } function evidenceValue(result, label) { const row = result.evidence.find((entry) => entry.label === label); return row ? row.value : undefined; } // --- no redirect: behaviour must be the old behaviour ---------------------------------------- test('a host with no redirect is inspected once and judged as before', async () => { const inspect = fakeInspect({ 'example.com': tlsInfo('example.com') }); const request = fakeRequest({ 'example.com': { status: 200, tls: tlsInfo('example.com').cert } }); const result = await checkTls('example.com', { inspect, request }); assert.equal(result.state, 'ok'); assert.equal(inspect.calls.length, 1, 'only the typed host gets a handshake'); assert.equal(request.calls.length, 1, 'one HEAD request discovers there is no redirect'); assert.equal(request.calls[0].method, 'HEAD'); assert.equal(evidenceValue(result, 'checked at'), 'https://example.com'); assert.equal(evidenceValue(result, 'redirects'), 'none'); assert.equal(evidenceValue(result, 'typed address'), undefined, 'no second address to name'); assert.ok(codes(result).includes('tls_name_match')); }); // --- apex -> www, one certificate covering both --------------------------------------------- test('an apex that redirects to www is judged at www, and the summary names it', async () => { const inspect = fakeInspect({ 'example.com': tlsInfo('example.com', { san: 'DNS:example.com, DNS:*.example.com' }) }); const request = fakeRequest({ 'example.com': { status: 301, headers: { location: 'https://www.example.com/' } }, 'www.example.com': { status: 200, tls: tlsInfo('www.example.com', { san: 'DNS:*.example.com' }).cert } }); const result = await checkTls('example.com', { inspect, request }); assert.equal(result.state, 'ok'); // The final certificate rides back on the redirect's own socket, so no second handshake. assert.equal(inspect.calls.length, 1); assert.equal(request.calls.length, 2); assert.match(result.summary, /www\.example\.com/); assert.equal(evidenceValue(result, 'checked at'), 'https://www.example.com/'); assert.equal(evidenceValue(result, 'typed address'), 'example.com'); assert.ok(String(evidenceValue(result, 'certificate at typed address')).includes('issued to example.com')); assert.ok(codes(result).includes('tls_redirect_typed_ok')); }); test('a problem on the typed certificate still counts when the redirect target is healthy', async () => { // A short chain does not stop a browser from loading the page, so this is the realistic shape of // "the first hop is imperfect but the site still redirects onwards". const inspect = fakeInspect({ 'example.com': tlsInfo('example.com', { includeIntermediate: false }) }); const request = fakeRequest({ 'example.com': { status: 301, headers: { location: 'https://www.example.com/' } }, 'www.example.com': { status: 200, tls: tlsInfo('www.example.com').cert } }); const result = await checkTls('example.com', { inspect, request }); assert.equal(result.state, 'warn'); assert.ok(codes(result).includes('tls_chain_short')); assert.match(result.summary, /example\.com/); assert.doesNotMatch(result.summary, /www\.example\.com is valid/i); }); // --- the broken certificate is at the end of the chain, where visitors land ------------------ test('a healthy typed host redirecting to an expired host fails, and the summary names the broken address', async () => { const expired = tlsInfo('www.example.com', { validTo: daysFromNow(-10) }); const inspect = fakeInspect({ 'example.com': tlsInfo('example.com'), 'www.example.com': expired }); const request = fakeRequest({ 'example.com': { status: 301, headers: { location: 'https://www.example.com/' } }, // rejectUnauthorized is on for a real request, so a broken certificate throws at the hop. 'www.example.com': () => { throw new NetGuardError('tls_expired', 'The certificate on that site has expired.'); } }); const result = await checkTls('example.com', { inspect, request }); assert.equal(result.state, 'fail'); assert.ok(codes(result).includes('tls_expired')); assert.match(result.summary, /www\.example\.com/); assert.match(result.summary, /expired/i); // Exactly one extra handshake: the typed host plus the host that actually failed. assert.equal(inspect.calls.length, 2); }); test('a name-mismatched certificate at the redirect target fails with the target named', async () => { const wrongName = tlsInfo('www.example.com', { san: 'DNS:other.example.net' }); const inspect = fakeInspect({ 'example.com': tlsInfo('example.com'), 'www.example.com': wrongName }); const request = fakeRequest({ 'example.com': { status: 302, headers: { location: 'https://www.example.com/' } }, 'www.example.com': () => { throw new NetGuardError('tls_invalid', 'The certificate on that site could not be verified.'); } }); const result = await checkTls('example.com', { inspect, request }); assert.equal(result.state, 'fail'); assert.ok(codes(result).includes('tls_name_mismatch')); assert.match(result.summary, /www\.example\.com/); }); // --- the redirect target is somewhere this service will not go ------------------------------ test('a redirect into a private address keeps the typed verdict and says the target was not checked', async () => { const inspect = fakeInspect({ 'example.com': tlsInfo('example.com') }); const request = fakeRequest({ 'example.com': { status: 301, headers: { location: 'http://192.168.1.1/' } } }); const result = await checkTls('example.com', { inspect, request }); assert.equal(result.state, 'ok', 'we did not look, so the typed host is not called broken'); assert.equal(request.calls.length, 1, 'the private target is never dialled'); assert.equal(inspect.calls.length, 1, 'and never handshaked'); const note = result.findings.find((finding) => finding.code === 'tls_redirect_unchecked'); assert.ok(note, 'the skipped target is recorded, not silently dropped'); assert.equal(note.level, 'info'); assert.match(note.message, /not checked/i); assert.match(note.message, /example\.com only/); assert.match(note.message, /IP address/); assert.doesNotMatch(note.message, /Enter a domain/); }); // --- a chain that never settles ------------------------------------------------------------- test('a redirect loop is bounded, adds no false failure, and says only the typed host was judged', async () => { const inspect = fakeInspect({ 'loop.example.com': tlsInfo('loop.example.com') }); const request = fakeRequest({ 'loop.example.com': { status: 301, headers: { location: 'https://loop2.example.com/' } }, 'loop2.example.com': { status: 301, headers: { location: 'https://loop.example.com/' } } }); const result = await checkTls('loop.example.com', { inspect, request }); assert.equal(result.state, 'ok'); assert.ok(request.calls.length <= 6, 'the walk stays inside the redirect cap'); assert.ok(codes(result).includes('tls_redirect_unresolved')); assert.match(result.summary, /valid/i); }); test('more than five redirects stops at the cap without throwing', async () => { const hosts = ['h1.example.com', 'h2.example.com', 'h3.example.com', 'h4.example.com', 'h5.example.com', 'h6.example.com', 'h7.example.com']; const routes = {}; for (let i = 0; i < hosts.length - 1; i += 1) { routes[hosts[i]] = { status: 301, headers: { location: `https://${hosts[i + 1]}/` } }; } routes[hosts[hosts.length - 1]] = { status: 200, tls: tlsInfo(hosts[hosts.length - 1]).cert }; const inspect = fakeInspect({ 'h1.example.com': tlsInfo('h1.example.com') }); const request = fakeRequest(routes); const result = await checkTls('h1.example.com', { inspect, request }); assert.equal(result.state, 'ok'); assert.equal(request.calls.length, 6, 'MAX_REDIRECTS + the first request, no more'); assert.ok(codes(result).includes('tls_redirect_unresolved')); }); // --- HEAD refusals and plain-http landings -------------------------------------------------- test('a server that refuses HEAD is asked again with a capped GET', async () => { const inspect = fakeInspect({ 'example.com': tlsInfo('example.com') }); const request = fakeRequest({ 'example.com': (options) => (options.method === 'HEAD' ? { status: 405, headers: {} } : { status: 200, tls: tlsInfo('example.com').cert }) }); const result = await checkTls('example.com', { inspect, request }); assert.equal(result.state, 'ok'); assert.deepEqual(request.calls.map((call) => call.method), ['HEAD', 'GET']); }); test('a redirect to plain http is recorded as no certificate there, not as a TLS failure', async () => { const inspect = fakeInspect({ 'example.com': tlsInfo('example.com') }); const request = fakeRequest({ 'example.com': { status: 301, headers: { location: 'http://other.example.com/' } }, 'other.example.com': { status: 200 } }); const result = await checkTls('example.com', { inspect, request }); assert.equal(result.state, 'ok'); assert.ok(codes(result).includes('tls_final_not_https')); assert.match(result.summary, /plain http/); }); // --- the hop that fails cannot even be read ------------------------------------------------- test('a TLS failure at a redirect target that cannot be inspected is still reported as a failure', async () => { const inspect = fakeInspect({ 'example.com': tlsInfo('example.com'), 'broken.example.com': new NetGuardError('timeout', 'The TLS handshake timed out.') }); const request = fakeRequest({ 'example.com': { status: 301, headers: { location: 'https://broken.example.com/' } }, 'broken.example.com': () => { throw new NetGuardError('tls_invalid', 'The certificate on that site could not be verified.'); } }); const result = await checkTls('example.com', { inspect, request }); assert.equal(result.state, 'fail'); const failed = result.findings.find((finding) => finding.code === 'tls_redirect_hop_failed'); assert.ok(failed); assert.equal(failed.level, 'fail'); assert.match(failed.message, /broken\.example\.com/); assert.match(result.summary, /broken\.example\.com/); }); // --- the discovery seam itself -------------------------------------------------------------- test('discoverFinalHost reports the final address and the trail without analysing anything', async () => { const request = fakeRequest({ 'example.com': { status: 301, headers: { location: 'https://www.example.com/' } }, 'www.example.com': { status: 200 } }); const found = await discoverFinalHost('example.com', { request }); assert.equal(found.finalHost, 'www.example.com'); assert.equal(found.stop, null); assert.equal(found.hops.length, 2); assert.equal(found.hops[0].status, 301); });