mail-transport recorded truncation but never surfaced it, so a policy file cut off at the 32 KB limit could still be reported as mode=enforce from a partial parse. hardening's CAA comparison matched issuer tokens blindly, so a certificate naming only its profile (CN: R11, no O) against a CAA record for another CA produced "a renewal would be refused" out of nothing. Both now say they could not judge instead.
699 lines
32 KiB
JavaScript
699 lines
32 KiB
JavaScript
import test from 'node:test';
|
|
import assert from 'node:assert/strict';
|
|
|
|
import {
|
|
analyseHardening,
|
|
analyseCompression,
|
|
analyseCookies,
|
|
checkHardening,
|
|
caaAuthorisesIssuer,
|
|
caaNames,
|
|
normaliseCaa,
|
|
parseSetCookie,
|
|
detectVersionBanner,
|
|
isSessionCookie,
|
|
worstLevel,
|
|
createRequestBudget,
|
|
describeFailure,
|
|
REQUEST_BUDGET,
|
|
PAGE_MAX_BYTES,
|
|
GUARD_HONOURS_COMPRESSION
|
|
} from '../src/checks/hardening.mjs';
|
|
import { NetGuardError } from '../src/lib/net-guard.mjs';
|
|
|
|
// Everything here is a fixture object and an injected fake. No server is started, no socket is
|
|
// opened, no name is resolved, and the clock is pinned with `now`.
|
|
const NOW = Date.UTC(2026, 0, 15, 12, 0, 0);
|
|
const ISO_NOW = '2026-01-15T12:00:00.000Z';
|
|
|
|
const CLEAN_HEADERS = {
|
|
'content-encoding': 'gzip',
|
|
'content-length': '18432',
|
|
vary: 'Accept-Encoding',
|
|
server: 'nginx',
|
|
'set-cookie': ['PHPSESSID=abc123; Path=/; HttpOnly; Secure; SameSite=Lax']
|
|
};
|
|
|
|
const LETS_ENCRYPT = { CN: 'R11', O: "Let's Encrypt" };
|
|
|
|
function facts(overrides = {}) {
|
|
return {
|
|
host: 'www.example.com',
|
|
url: 'https://www.example.com/',
|
|
response: {
|
|
status: 200,
|
|
headers: { ...CLEAN_HEADERS },
|
|
bodyBytes: 96411,
|
|
truncated: false
|
|
},
|
|
compression: {
|
|
contentEncoding: 'gzip',
|
|
contentLength: 18432,
|
|
receivedBytes: 18432,
|
|
decodedBytes: 96411,
|
|
requestedEncoding: 'br, gzip',
|
|
honoured: true,
|
|
vary: 'Accept-Encoding'
|
|
},
|
|
caa: { name: 'example.com', records: [{ critical: 0, issue: 'letsencrypt.org' }] },
|
|
certificate: { issuer: LETS_ENCRYPT },
|
|
...overrides
|
|
};
|
|
}
|
|
|
|
const codes = (result) => result.findings.map((finding) => finding.code);
|
|
const levelOf = (result, code) => (result.findings.find((finding) => finding.code === code) || {}).level;
|
|
|
|
/** A fake transport: net-guard's requestOnce signature, no network. */
|
|
function fakeRequest(responses) {
|
|
const calls = [];
|
|
const list = Array.isArray(responses) ? responses : [responses];
|
|
const fn = async (url, options = {}) => {
|
|
calls.push({ url, options });
|
|
const next = list[Math.min(calls.length - 1, list.length - 1)];
|
|
if (typeof next === 'function') return next(url, options);
|
|
if (next instanceof Error) throw next;
|
|
return { url, status: 200, headers: {}, body: '', truncated: false, tls: null, timing: { totalMs: 12 }, ...next };
|
|
};
|
|
fn.calls = calls;
|
|
return fn;
|
|
}
|
|
|
|
function fakeDns(records, { throwOn = null } = {}) {
|
|
const asked = [];
|
|
return {
|
|
asked,
|
|
async resolveCaa(name) {
|
|
asked.push(name);
|
|
if (throwOn) {
|
|
const err = new Error('no record');
|
|
err.code = throwOn;
|
|
throw err;
|
|
}
|
|
if (typeof records === 'function') return records(name);
|
|
if (!records) {
|
|
const err = new Error('no record');
|
|
err.code = 'ENODATA';
|
|
throw err;
|
|
}
|
|
return records;
|
|
}
|
|
};
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------------------------
|
|
// envelope shape
|
|
// ---------------------------------------------------------------------------------------------
|
|
|
|
test('envelope carries the contract keys and an ISO checkedAt, not epoch ms', () => {
|
|
const result = analyseHardening(facts(), { now: NOW });
|
|
assert.deepEqual(
|
|
Object.keys(result).sort(),
|
|
['checkedAt', 'evidence', 'findings', 'fromCache', 'id', 'state', 'summary'].sort()
|
|
);
|
|
assert.equal(result.id, 'hardening');
|
|
assert.equal(result.checkedAt, ISO_NOW);
|
|
assert.equal(typeof result.checkedAt, 'string');
|
|
assert.match(result.checkedAt, /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/);
|
|
assert.equal(result.fromCache, false);
|
|
assert.equal(typeof result.summary, 'string');
|
|
assert.ok(result.summary.length > 0);
|
|
for (const row of result.evidence) {
|
|
assert.equal(typeof row.label, 'string');
|
|
assert.equal(typeof row.value, 'string');
|
|
}
|
|
for (const finding of result.findings) {
|
|
assert.ok(['ok', 'info', 'warn', 'fail'].includes(finding.level));
|
|
assert.equal(typeof finding.code, 'string');
|
|
assert.equal(typeof finding.message, 'string');
|
|
assert.ok(finding.message.length > 10);
|
|
}
|
|
});
|
|
|
|
test('a fully clean page is state ok with four positive codes', () => {
|
|
const result = analyseHardening(facts(), { now: NOW });
|
|
assert.equal(result.state, 'ok');
|
|
assert.deepEqual(codes(result), [
|
|
'hardening_compression_on',
|
|
'hardening_caa_authorises_issuer',
|
|
'hardening_cookies_flagged',
|
|
'hardening_no_version_banner'
|
|
]);
|
|
assert.ok(result.summary.startsWith('Checked how this page is served:'));
|
|
});
|
|
|
|
test('state equals the worst finding, with info folded into ok', () => {
|
|
assert.equal(worstLevel([{ level: 'ok' }, { level: 'info' }]), 'ok');
|
|
assert.equal(worstLevel([{ level: 'info' }, { level: 'warn' }]), 'warn');
|
|
assert.equal(worstLevel([]), 'ok');
|
|
const withWarning = analyseHardening(
|
|
facts({ response: { status: 200, headers: { 'set-cookie': ['JSESSIONID=1; Path=/'] }, bodyBytes: 900 } }),
|
|
{ now: NOW }
|
|
);
|
|
assert.equal(withWarning.state, 'warn');
|
|
});
|
|
|
|
test('there is no score, no grade and no "at risk" phrasing anywhere', () => {
|
|
const result = analyseHardening(facts(), { now: NOW });
|
|
assert.equal(result.score, undefined);
|
|
assert.equal(result.grade, undefined);
|
|
assert.equal(result.rating, undefined);
|
|
for (const finding of result.findings) {
|
|
assert.doesNotMatch(finding.message, /at risk|security score|grade|points|\b\d+\s*\/\s*100\b/i);
|
|
}
|
|
assert.doesNotMatch(result.summary, /at risk|security score|grade/i);
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------------------------
|
|
// question 1 — compression
|
|
// ---------------------------------------------------------------------------------------------
|
|
|
|
test('measured compression reports the real saving it computed', () => {
|
|
const result = analyseHardening(facts(), { now: NOW });
|
|
const finding = result.findings.find((f) => f.code === 'hardening_compression_on');
|
|
assert.equal(finding.level, 'ok');
|
|
// 1 - 18432/96411 = 0.8088…
|
|
assert.match(finding.message, /about 81% smaller/);
|
|
assert.match(finding.message, /18\.0 KB/);
|
|
assert.match(finding.message, /94\.2 KB/);
|
|
const row = result.evidence.find((r) => r.label === 'compression');
|
|
assert.match(row.value, /gzip/);
|
|
assert.match(row.value, /81% smaller/);
|
|
});
|
|
|
|
test('Content-Length absent: says "compressed" with no percentage, and never invents a saving', () => {
|
|
const result = analyseHardening(
|
|
facts({
|
|
response: { status: 200, headers: { 'content-encoding': 'br' }, bodyBytes: 12000 },
|
|
compression: { contentEncoding: 'br', contentLength: null, receivedBytes: 12000, decodedBytes: null, honoured: true }
|
|
}),
|
|
{ now: NOW }
|
|
);
|
|
const finding = result.findings.find((f) => f.code === 'hardening_compression_on_unmeasured');
|
|
assert.equal(finding.level, 'ok');
|
|
assert.match(finding.message, /sent the page br-compressed/);
|
|
assert.match(finding.message, /not measured/);
|
|
assert.doesNotMatch(finding.message, /instead of|smaller\.|%/);
|
|
});
|
|
|
|
test('compression measured but larger than the plain page: no gain, never a failure', () => {
|
|
const result = analyseHardening(
|
|
facts({
|
|
compression: { contentEncoding: 'gzip', contentLength: 412, receivedBytes: 412, decodedBytes: 398, honoured: true }
|
|
}),
|
|
{ now: NOW }
|
|
);
|
|
assert.equal(levelOf(result, 'hardening_compression_no_gain'), 'info');
|
|
assert.equal(result.state, 'ok');
|
|
});
|
|
|
|
test('no compression, asked for it: info, not a failure', () => {
|
|
const result = analyseHardening(
|
|
facts({
|
|
response: { status: 200, headers: { 'content-length': '51200' }, bodyBytes: 51200 },
|
|
compression: { contentEncoding: null, contentLength: 51200, receivedBytes: 51200, decodedBytes: 51200, honoured: true }
|
|
}),
|
|
{ now: NOW }
|
|
);
|
|
assert.equal(levelOf(result, 'hardening_compression_off'), 'info');
|
|
assert.equal(result.state, 'ok');
|
|
assert.ok(!result.findings.some((f) => f.level === 'fail'));
|
|
});
|
|
|
|
test('compression not asked for (net-guard asks identity): reported as not measured, not as absent', () => {
|
|
const result = analyseHardening(
|
|
facts({
|
|
response: { status: 200, headers: { 'content-length': '51200' }, bodyBytes: 51200 },
|
|
compression: { contentEncoding: null, contentLength: 51200, receivedBytes: 51200, honoured: false }
|
|
}),
|
|
{ now: NOW }
|
|
);
|
|
assert.equal(levelOf(result, 'hardening_compression_not_measured'), 'info');
|
|
assert.ok(!codes(result).includes('hardening_compression_off'));
|
|
assert.equal(result.state, 'ok');
|
|
});
|
|
|
|
// The flag is a claim about net-guard, so it is checked against net-guard's own source rather
|
|
// than against itself: the day someone removes the option, this fails instead of the check
|
|
// quietly reporting "not measured" forever.
|
|
test('compression is asked for, and net-guard really accepts the option', async () => {
|
|
const { readFile } = await import('node:fs/promises');
|
|
const guard = await readFile(new URL('../src/lib/net-guard.mjs', import.meta.url), 'utf8');
|
|
assert.equal(GUARD_HONOURS_COMPRESSION, true);
|
|
assert.match(guard, /acceptEncoding = 'identity'/);
|
|
assert.match(guard, /'accept-encoding': acceptEncoding/);
|
|
assert.match(guard, /decodedBytes/);
|
|
});
|
|
|
|
test('Vary: Accept-Encoding with an identity answer is reported as offered, not measured', () => {
|
|
const result = analyseHardening(
|
|
facts({
|
|
response: { status: 200, headers: { vary: 'Accept-Encoding', 'content-length': '900' }, bodyBytes: 900 },
|
|
compression: { contentEncoding: null, contentLength: 900, receivedBytes: 900, honoured: false, vary: 'Accept-Encoding' }
|
|
}),
|
|
{ now: NOW }
|
|
);
|
|
assert.equal(levelOf(result, 'hardening_compression_available'), 'info');
|
|
assert.equal(result.state, 'ok');
|
|
});
|
|
|
|
test('analyseCompression does the arithmetic and refuses to guess', () => {
|
|
const measured = analyseCompression({ contentEncoding: 'gzip', contentLength: 2500, receivedBytes: 2500, decodedBytes: 10000 });
|
|
assert.equal(measured.measured, true);
|
|
assert.equal(measured.savingPercent, 75);
|
|
assert.equal(measured.savedBytes, 7500);
|
|
|
|
const half = analyseCompression({ contentEncoding: 'gzip', receivedBytes: 2500, decodedBytes: null });
|
|
assert.equal(half.measured, false);
|
|
assert.equal(half.savingPercent, null);
|
|
|
|
const identity = analyseCompression({ contentEncoding: 'identity', contentLength: 10, decodedBytes: 10 });
|
|
assert.equal(identity.encoding, null);
|
|
assert.equal(identity.measured, false);
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------------------------
|
|
// question 2 — CAA
|
|
// ---------------------------------------------------------------------------------------------
|
|
|
|
test('no CAA record is info and says plainly it is not a fault', () => {
|
|
const result = analyseHardening(facts({ caa: { name: null, records: [], error: null } }), { now: NOW });
|
|
const finding = result.findings.find((f) => f.code === 'hardening_caa_absent');
|
|
assert.equal(finding.level, 'info');
|
|
assert.match(finding.message, /any certificate authority may issue/);
|
|
assert.match(finding.message, /not a fault/);
|
|
assert.equal(result.state, 'ok');
|
|
});
|
|
|
|
test('CAA present but the certificate could not be read: record reported, comparison not made', () => {
|
|
const result = analyseHardening(facts({ certificate: null }), { now: NOW });
|
|
const finding = result.findings.find((f) => f.code === 'hardening_caa_not_compared');
|
|
assert.equal(finding.level, 'info');
|
|
assert.match(finding.message, /were not compared/);
|
|
assert.ok(result.evidence.some((row) => row.label === 'CAA' && row.value.includes('letsencrypt.org')));
|
|
assert.equal(result.state, 'ok');
|
|
});
|
|
|
|
test('CAA that does not name the issuing CA is a warn, never a fail', () => {
|
|
const result = analyseHardening(
|
|
facts({ caa: { name: 'example.com', records: [{ critical: 0, issue: 'digicert.com' }] } }),
|
|
{ now: NOW }
|
|
);
|
|
const finding = result.findings.find((f) => f.code === 'hardening_caa_issuer_mismatch');
|
|
assert.equal(finding.level, 'warn');
|
|
assert.match(finding.message, /issued by Let's Encrypt/);
|
|
assert.match(finding.message, /only allows digicert\.com/);
|
|
assert.equal(result.state, 'warn');
|
|
assert.notEqual(result.state, 'fail');
|
|
assert.ok(!result.findings.some((f) => f.level === 'fail'));
|
|
});
|
|
|
|
test('CAA issue ";" with a certificate being served is info, not an accusation', () => {
|
|
const result = analyseHardening(
|
|
facts({ caa: { name: 'example.com', records: [{ critical: 0, issue: ';' }] } }),
|
|
{ now: NOW }
|
|
);
|
|
assert.equal(levelOf(result, 'hardening_caa_deny_all'), 'info');
|
|
assert.equal(result.state, 'ok');
|
|
assert.ok(!codes(result).includes('hardening_caa_issuer_mismatch'));
|
|
});
|
|
|
|
test('CAA lookup that could not run is info and leaves the other three answers intact', () => {
|
|
const result = analyseHardening(facts({ caa: { name: null, records: [], error: 'no resolver' } }), { now: NOW });
|
|
assert.equal(levelOf(result, 'hardening_caa_unavailable'), 'info');
|
|
assert.ok(codes(result).includes('hardening_compression_on'));
|
|
assert.ok(codes(result).includes('hardening_cookies_flagged'));
|
|
assert.equal(result.state, 'ok');
|
|
});
|
|
|
|
test('CAA comparison understands the CAs small sites actually use', () => {
|
|
assert.equal(caaAuthorisesIssuer([{ issue: 'letsencrypt.org' }], LETS_ENCRYPT).status, 'match');
|
|
assert.equal(caaAuthorisesIssuer([{ issue: 'digicert.com' }], { CN: 'DigiCert TLS RSA SHA256 2020 CA1', O: 'DigiCert Inc' }).status, 'match');
|
|
assert.equal(caaAuthorisesIssuer([{ issue: 'sectigo.com' }], { CN: 'R36', O: 'ZeroSSL' }).status, 'match');
|
|
assert.equal(caaAuthorisesIssuer([{ issue: 'pki.goog' }], { CN: 'GTS CA 1P5', O: 'Google Trust Services' }).status, 'match');
|
|
assert.equal(caaAuthorisesIssuer([{ issue: 'letsencrypt.org' }], { CN: 'R11', O: 'DigiCert Inc' }).status, 'mismatch');
|
|
assert.equal(caaAuthorisesIssuer([{ issue: 'letsencrypt.org' }], null).status, 'no-issuer');
|
|
assert.equal(caaAuthorisesIssuer([], LETS_ENCRYPT).status, 'no-caa');
|
|
assert.equal(caaAuthorisesIssuer([{ issue: ';' }], LETS_ENCRYPT).status, 'deny-all');
|
|
});
|
|
|
|
test('CAA parameters and raw record strings are both understood', () => {
|
|
const parsed = normaliseCaa(['0 issue "letsencrypt.org; validationmethods=dns-01"', '0 iodef "mailto:[email protected]"']);
|
|
assert.deepEqual(parsed[0], { issue: 'letsencrypt.org; validationmethods=dns-01' });
|
|
assert.deepEqual(parsed[1], { iodef: 'mailto:[email protected]' });
|
|
const policy = caaAuthorisesIssuer(parsed, LETS_ENCRYPT);
|
|
assert.equal(policy.status, 'match');
|
|
assert.deepEqual(policy.allowed, ['letsencrypt.org']);
|
|
});
|
|
|
|
test('the CAA walk stops at the registrable name, com.my included', () => {
|
|
assert.deepEqual(caaNames('www.example.com'), ['www.example.com', 'example.com']);
|
|
assert.deepEqual(caaNames('example.com.my'), ['example.com.my']);
|
|
assert.deepEqual(caaNames('shop.example.com.my'), ['shop.example.com.my', 'example.com.my']);
|
|
assert.deepEqual(caaNames('a.b.c.example.com'), ['a.b.c.example.com', 'b.c.example.com', 'c.example.com', 'example.com']);
|
|
assert.deepEqual(caaNames('example'), []);
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------------------------
|
|
// question 3 — cookies
|
|
// ---------------------------------------------------------------------------------------------
|
|
|
|
test('a session cookie without Secure is a warn and names the consequence', () => {
|
|
const result = analyseHardening(
|
|
facts({ response: { status: 200, headers: { 'set-cookie': ['PHPSESSID=abc; Path=/; HttpOnly'] }, bodyBytes: 800 } }),
|
|
{ now: NOW }
|
|
);
|
|
const finding = result.findings.find((f) => f.code === 'hardening_cookie_missing_flag');
|
|
assert.equal(finding.level, 'warn');
|
|
assert.match(finding.message, /PHPSESSID/);
|
|
assert.match(finding.message, /without Secure/);
|
|
assert.match(finding.message, /plain http/);
|
|
assert.equal(result.state, 'warn');
|
|
});
|
|
|
|
test('a session cookie without HttpOnly is a warn; both missing is still one warn per cookie', () => {
|
|
const result = analyseHardening(
|
|
facts({ response: { status: 200, headers: { 'set-cookie': ['laravel_session=x; Path=/'] }, bodyBytes: 800 } }),
|
|
{ now: NOW }
|
|
);
|
|
const warns = result.findings.filter((f) => f.code === 'hardening_cookie_missing_flag');
|
|
assert.equal(warns.length, 1);
|
|
assert.equal(warns[0].level, 'warn');
|
|
assert.match(warns[0].message, /HttpOnly and Secure/);
|
|
assert.equal(result.state, 'warn');
|
|
});
|
|
|
|
test('an analytics cookie without flags is info only', () => {
|
|
const result = analyseHardening(
|
|
facts({ response: { status: 200, headers: { 'set-cookie': ['_ga=GA1.1.2.3; Path=/; Max-Age=63072000'] }, bodyBytes: 800 } }),
|
|
{ now: NOW }
|
|
);
|
|
assert.equal(levelOf(result, 'hardening_cookie_optional_flag'), 'info');
|
|
assert.ok(!result.findings.some((f) => f.level === 'warn'));
|
|
assert.equal(result.state, 'ok');
|
|
});
|
|
|
|
test('a well-flagged session cookie with no SameSite is info, not a warning', () => {
|
|
const result = analyseHardening(
|
|
facts({ response: { status: 200, headers: { 'set-cookie': ['PHPSESSID=abc; Path=/; HttpOnly; Secure'] }, bodyBytes: 800 } }),
|
|
{ now: NOW }
|
|
);
|
|
assert.equal(levelOf(result, 'hardening_cookie_no_samesite'), 'info');
|
|
assert.equal(levelOf(result, 'hardening_cookies_flagged'), 'ok');
|
|
assert.equal(result.state, 'ok');
|
|
});
|
|
|
|
test('no cookies at all is info, and parseSetCookie reads every flag', () => {
|
|
const result = analyseHardening(
|
|
facts({ response: { status: 200, headers: { 'content-encoding': 'gzip' }, bodyBytes: 800 } }),
|
|
{ now: NOW }
|
|
);
|
|
assert.equal(levelOf(result, 'hardening_cookies_none'), 'info');
|
|
|
|
const cookie = parseSetCookie('sid=1; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=3600');
|
|
assert.equal(cookie.name, 'sid');
|
|
assert.equal(cookie.httpOnly, true);
|
|
assert.equal(cookie.secure, true);
|
|
assert.equal(cookie.sameSite, 'Strict');
|
|
assert.equal(cookie.maxAge, 3600);
|
|
assert.equal(isSessionCookie(cookie), true);
|
|
assert.equal(isSessionCookie(parseSetCookie('_gid=1; Max-Age=86400')), false);
|
|
assert.equal(isSessionCookie(parseSetCookie('theme=dark; Max-Age=86400')), false);
|
|
assert.equal(isSessionCookie(parseSetCookie('theme=dark')), true, 'no expiry means a session cookie');
|
|
});
|
|
|
|
test('analyseCookies handles a string set-cookie as well as an array', () => {
|
|
const one = analyseCookies(['sid=1; HttpOnly']);
|
|
const many = analyseCookies(['sid=1; HttpOnly', 'other=2']);
|
|
assert.equal(one.findings.filter((f) => f.code === 'hardening_cookie_missing_flag').length, 1);
|
|
assert.equal(many.findings.filter((f) => f.code === 'hardening_cookie_missing_flag').length, 2);
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------------------------
|
|
// question 4 — version banners
|
|
// ---------------------------------------------------------------------------------------------
|
|
|
|
test('a version banner is info, never a failure', () => {
|
|
const result = analyseHardening(
|
|
facts({ response: { status: 200, headers: { server: 'nginx/1.18.0', 'content-encoding': 'gzip' }, bodyBytes: 900 } }),
|
|
{ now: NOW }
|
|
);
|
|
const finding = result.findings.find((f) => f.code === 'hardening_version_banner');
|
|
assert.equal(finding.level, 'info');
|
|
assert.match(finding.message, /Server: nginx\/1\.18\.0/);
|
|
assert.equal(result.state, 'ok');
|
|
});
|
|
|
|
test('detectVersionBanner picks the three headers that leak a version and ignores a bare product name', () => {
|
|
assert.deepEqual(detectVersionBanner({ server: 'nginx/1.18.0' }), [{ header: 'Server', value: 'nginx/1.18.0' }]);
|
|
assert.deepEqual(detectVersionBanner({ 'x-powered-by': 'PHP/7.4.33' }), [{ header: 'X-Powered-By', value: 'PHP/7.4.33' }]);
|
|
assert.deepEqual(detectVersionBanner({ 'x-aspnet-version': '4.0.30319.42000' }), [
|
|
{ header: 'X-AspNet-Version', value: '4.0.30319.42000' }
|
|
]);
|
|
assert.deepEqual(detectVersionBanner({ server: 'cloudflare' }), []);
|
|
assert.deepEqual(detectVersionBanner({ server: 'nginx' }), []);
|
|
assert.deepEqual(detectVersionBanner({}), []);
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------------------------
|
|
// blocked, broken and unreadable — never a red verdict
|
|
// ---------------------------------------------------------------------------------------------
|
|
|
|
const NOT_EVALUATED_CASES = [
|
|
['403 firewall', facts({ response: { status: 403, headers: { 'cf-ray': 'x' }, bodyBytes: 40 }, blocked: { blocked: true, reason: 'status 403' } })],
|
|
['429 rate limit', facts({ response: { status: 429, headers: {}, bodyBytes: 40 }, blocked: { blocked: true, reason: 'status 429' } })],
|
|
['bot challenge', facts({ response: { status: 200, headers: { 'cf-ray': 'x' }, bodyBytes: 900 }, blocked: { blocked: true, reason: 'bot challenge (CDN)' } })],
|
|
['timeout', { host: 'example.com', error: { code: 'timeout' } }],
|
|
['SERVFAIL', { host: 'example.com', error: { code: 'dns_timeout' } }],
|
|
['NXDOMAIN', { host: 'example.com', error: { code: 'dns_nxdomain' } }],
|
|
['no response at all', { host: 'example.com', response: null }]
|
|
];
|
|
|
|
for (const [label, scenario] of NOT_EVALUATED_CASES) {
|
|
test(`${label} is not-evaluated with zero findings against the site`, () => {
|
|
const result = analyseHardening(scenario, { now: NOW });
|
|
assert.equal(result.state, 'not-evaluated');
|
|
assert.deepEqual(result.findings, []);
|
|
assert.equal(result.checkedAt, ISO_NOW);
|
|
assert.doesNotMatch(result.summary, /insecure|vulnerable|at risk|failed/i);
|
|
assert.ok(result.summary.length > 20);
|
|
});
|
|
}
|
|
|
|
test('describeFailure never blames the visitor for a firewall or a timeout', () => {
|
|
for (const code of ['timeout', 'dns_timeout', 'dns_nxdomain', 'refused', 'tls_invalid', 'tls_expired']) {
|
|
const text = describeFailure({ code });
|
|
assert.doesNotMatch(text, /insecure|vulnerable|at risk/i);
|
|
assert.match(text, /nothing was judged|nothing to look at|no page to look at|was not read/i);
|
|
}
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------------------------
|
|
// the network half — one fake, no sockets
|
|
// ---------------------------------------------------------------------------------------------
|
|
|
|
test('one page GET, explicit Accept, compression asked for, 256 KB cap', async () => {
|
|
const request = fakeRequest({ status: 200, headers: { ...CLEAN_HEADERS }, body: 'x'.repeat(900), tls: { issuer: LETS_ENCRYPT } });
|
|
const result = await checkHardening('www.example.com', {
|
|
request,
|
|
dns: fakeDns([{ critical: 0, issue: 'letsencrypt.org' }]),
|
|
now: NOW
|
|
});
|
|
|
|
assert.equal(request.calls.length, 1, 'exactly one outbound request');
|
|
const { url, options } = request.calls[0];
|
|
assert.equal(url, 'https://www.example.com/');
|
|
assert.equal(options.accept, 'text/html,application/xhtml+xml;q=0.9,*/*;q=0.5');
|
|
assert.equal(options.acceptEncoding, 'br, gzip');
|
|
assert.equal(options.maxBytes, PAGE_MAX_BYTES);
|
|
assert.equal(PAGE_MAX_BYTES, 256 * 1024);
|
|
assert.equal(result.state, 'ok');
|
|
assert.equal(result.checkedAt, ISO_NOW);
|
|
assert.equal(result.fromCache, false);
|
|
});
|
|
|
|
test('the certificate comes off the same response — no second connection for the CAA comparison', async () => {
|
|
const request = fakeRequest({ status: 200, headers: {}, body: 'ok', tls: { issuer: LETS_ENCRYPT } });
|
|
const result = await checkHardening('example.com', { request, dns: fakeDns([{ issue: 'letsencrypt.org' }]), now: NOW });
|
|
assert.equal(request.calls.length, 1);
|
|
assert.equal(levelOf(result, 'hardening_caa_authorises_issuer'), 'ok');
|
|
});
|
|
|
|
test('CAA is read for the typed host and falls back up the tree', async () => {
|
|
const request = fakeRequest({ status: 200, headers: {}, body: 'ok' });
|
|
const resolver = {
|
|
asked: [],
|
|
async resolveCaa(name) {
|
|
resolver.asked.push(name);
|
|
if (name === 'example.com') return [{ issue: 'letsencrypt.org' }];
|
|
const err = new Error('no data');
|
|
err.code = 'ENODATA';
|
|
throw err;
|
|
}
|
|
};
|
|
const result = await checkHardening('www.example.com', { request, dns: resolver, now: NOW });
|
|
assert.deepEqual(resolver.asked, ['www.example.com', 'example.com']);
|
|
assert.ok(result.evidence.some((row) => row.label === 'CAA' && row.value.startsWith('example.com:')));
|
|
});
|
|
|
|
test('a redirect is followed once, through the guard, and both slots of the budget are used', async () => {
|
|
const request = fakeRequest([
|
|
{ status: 301, headers: { location: 'https://www.example.com/' }, body: '' },
|
|
{ status: 200, headers: { ...CLEAN_HEADERS }, body: 'x'.repeat(500), tls: { issuer: LETS_ENCRYPT } }
|
|
]);
|
|
const result = await checkHardening('example.com', { request, dns: fakeDns([{ issue: 'letsencrypt.org' }]), now: NOW });
|
|
assert.equal(request.calls.length, 2);
|
|
assert.equal(request.calls[1].url, 'https://www.example.com/');
|
|
assert.equal(result.state, 'ok');
|
|
assert.equal(REQUEST_BUDGET, 2);
|
|
});
|
|
|
|
test('a redirect to a port the guard refuses is not followed, and that is info', async () => {
|
|
const request = fakeRequest({ status: 301, headers: { location: 'https://example.com:8443/x' }, body: '' });
|
|
const result = await checkHardening('example.com', { request, dns: fakeDns([{ issue: 'letsencrypt.org' }]), now: NOW });
|
|
assert.equal(request.calls.length, 1);
|
|
assert.equal(levelOf(result, 'hardening_redirect_not_followed'), 'info');
|
|
assert.equal(result.state, 'ok');
|
|
});
|
|
|
|
test('a second redirect is reported rather than chased', async () => {
|
|
const request = fakeRequest([
|
|
{ status: 301, headers: { location: 'https://www.example.com/' }, body: '' },
|
|
{ status: 302, headers: { location: 'https://www.example.com/en/' }, body: '' }
|
|
]);
|
|
const result = await checkHardening('example.com', { request, dns: fakeDns([{ issue: 'letsencrypt.org' }]), now: NOW });
|
|
assert.equal(request.calls.length, 2);
|
|
assert.equal(levelOf(result, 'hardening_redirect_chain'), 'info');
|
|
});
|
|
|
|
test('a 403 from the real fake transport is not-evaluated with no findings', async () => {
|
|
const request = fakeRequest({ status: 403, headers: { server: 'nginx/1.18.0' }, body: '<h1>Forbidden</h1>' });
|
|
const result = await checkHardening('example.com', { request, dns: fakeDns([{ issue: 'letsencrypt.org' }]), now: NOW });
|
|
assert.equal(result.state, 'not-evaluated');
|
|
assert.deepEqual(result.findings, []);
|
|
assert.match(result.summary, /firewall|normal protection/);
|
|
});
|
|
|
|
test('a bot challenge page is not-evaluated even on a 200', async () => {
|
|
const request = fakeRequest({ status: 200, headers: { 'cf-ray': 'abc' }, body: '<title>Just a moment...</title>' });
|
|
const result = await checkHardening('example.com', { request, dns: fakeDns(null), now: NOW });
|
|
assert.equal(result.state, 'not-evaluated');
|
|
assert.deepEqual(result.findings, []);
|
|
});
|
|
|
|
test('a thrown NetGuardError becomes not-evaluated, not an exception', async () => {
|
|
const request = fakeRequest(new NetGuardError('timeout', 'The site did not answer in time.'));
|
|
const result = await checkHardening('example.com', { request, dns: fakeDns(null), now: NOW });
|
|
assert.equal(result.state, 'not-evaluated');
|
|
assert.deepEqual(result.findings, []);
|
|
assert.ok(result.evidence.some((row) => row.label === 'reason' && row.value === 'timeout'));
|
|
assert.equal(result.checkedAt, ISO_NOW);
|
|
});
|
|
|
|
test('a private address is refused before any request is made', async () => {
|
|
const request = fakeRequest({ status: 200, headers: {}, body: '' });
|
|
const result = await checkHardening('127.0.0.1', { request, dns: fakeDns(null), now: NOW });
|
|
assert.equal(result.state, 'not-evaluated');
|
|
assert.equal(request.calls.length, 0);
|
|
assert.ok(result.evidence.some((row) => row.label === 'reason' && row.value === 'ip_literal'));
|
|
assert.deepEqual(Object.keys(result).sort(), ['checkedAt', 'evidence', 'findings', 'fromCache', 'id', 'state', 'summary'].sort());
|
|
});
|
|
|
|
test('a resolver without resolveCaa is reported as unavailable, not as "no CAA record"', async () => {
|
|
const request = fakeRequest({ status: 200, headers: {}, body: 'ok' });
|
|
const result = await checkHardening('example.com', { request, dns: {}, now: NOW });
|
|
assert.equal(levelOf(result, 'hardening_caa_unavailable'), 'info');
|
|
assert.ok(!codes(result).includes('hardening_caa_absent'));
|
|
});
|
|
|
|
test('a SERVFAIL on CAA is unavailable, and the page answers still stand', async () => {
|
|
const request = fakeRequest({ status: 200, headers: { 'content-encoding': 'gzip', 'content-length': '10' }, body: 'x'.repeat(90) });
|
|
const result = await checkHardening('example.com', { request, dns: fakeDns(null, { throwOn: 'ESERVFAIL' }), now: NOW });
|
|
assert.equal(levelOf(result, 'hardening_caa_unavailable'), 'info');
|
|
assert.ok(codes(result).includes('hardening_compression_on_unmeasured'));
|
|
});
|
|
|
|
test('the real transport is never called when a fake is injected, and the analyser never calls one', async () => {
|
|
// If checkHardening reached for the real requestOnce, this test would open a socket. It cannot:
|
|
// `request` is always the injected fake here, and analyseHardening takes no transport at all.
|
|
const request = fakeRequest({ status: 200, headers: {}, body: 'ok' });
|
|
await checkHardening('example.com', { request, dns: fakeDns(null), now: NOW });
|
|
assert.equal(request.calls.length, 1);
|
|
// The analyser is synchronous and takes no transport at all: it cannot reach the network.
|
|
const pure = analyseHardening(facts(), { now: NOW });
|
|
assert.ok(!(pure instanceof Promise));
|
|
assert.equal(pure.id, 'hardening');
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------------------------
|
|
// budget enforcement
|
|
// ---------------------------------------------------------------------------------------------
|
|
|
|
test('the request budget is a code-level cap, not a comment', () => {
|
|
const budget = createRequestBudget(2);
|
|
assert.equal(budget.spend('first'), 1);
|
|
assert.equal(budget.spend('second'), 2);
|
|
assert.throws(() => budget.spend('third'), (err) => {
|
|
assert.equal(err.code, 'budget_exhausted');
|
|
assert.match(err.message, /2-request budget/);
|
|
return true;
|
|
});
|
|
assert.equal(budget.remaining, 0);
|
|
});
|
|
|
|
test('a budget of one makes a redirect follow fail closed', async () => {
|
|
// The module builds its own budget, so this proves the mechanism the module uses rather than
|
|
// reaching into it: one spend, then a second is refused.
|
|
const budget = createRequestBudget(1);
|
|
budget.spend('page fetch');
|
|
assert.throws(() => budget.spend('redirect follow'), /budget_exhausted|budget/);
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------------------------
|
|
// invariants across every scenario
|
|
// ---------------------------------------------------------------------------------------------
|
|
|
|
test('no scenario in this file can reach state "fail"', () => {
|
|
const scenarios = [
|
|
facts(),
|
|
facts({ caa: { name: null, records: [], error: null } }),
|
|
facts({ caa: { name: 'example.com', records: [{ issue: 'digicert.com' }] } }),
|
|
facts({ certificate: null }),
|
|
facts({ response: { status: 200, headers: { 'set-cookie': ['sid=1'] }, bodyBytes: 900 } }),
|
|
facts({ response: { status: 200, headers: { server: 'nginx/1.18.0', 'x-powered-by': 'PHP/7.4.33' }, bodyBytes: 900 } }),
|
|
facts({ compression: { contentEncoding: null, contentLength: 900, receivedBytes: 900, honoured: true } }),
|
|
{ host: 'example.com', response: null },
|
|
{ host: 'example.com', error: { code: 'timeout' } }
|
|
];
|
|
for (const scenario of scenarios) {
|
|
const result = analyseHardening(scenario, { now: NOW });
|
|
assert.notEqual(result.state, 'fail', `scenario reached fail: ${JSON.stringify(scenario.response || scenario.error)}`);
|
|
assert.ok(['ok', 'warn', 'not-evaluated'].includes(result.state));
|
|
}
|
|
});
|
|
|
|
test('a CAA mismatch is never claimed from a profile identifier like R11', () => {
|
|
// Let's Encrypt certificates often carry only "R11"/"E6" as CN, with no O and no company name.
|
|
// Comparing that to a CAA record naming another CA would invent "your renewal would be refused".
|
|
const result = analyseHardening(
|
|
facts({
|
|
certificate: { issuer: { CN: 'R11' } },
|
|
caa: { name: 'example.com', records: [{ critical: 0, issue: 'digicert.com' }] }
|
|
}),
|
|
{ now: NOW }
|
|
);
|
|
assert.equal(result.findings.find((f) => f.code === 'hardening_caa_issuer_mismatch'), undefined);
|
|
assert.ok(result.findings.some((f) => f.code === 'hardening_caa_not_compared'));
|
|
});
|
|
|
|
test('a real company name still produces the mismatch warning', () => {
|
|
const result = analyseHardening(
|
|
facts({
|
|
certificate: { issuer: LETS_ENCRYPT },
|
|
caa: { name: 'example.com', records: [{ critical: 0, issue: 'digicert.com' }] }
|
|
}),
|
|
{ now: NOW }
|
|
);
|
|
assert.ok(result.findings.some((f) => f.code === 'hardening_caa_issuer_mismatch'));
|
|
});
|