"use strict"; // adpanel:force-https-coverage — pins for the FORCE_HTTPS redirect mount // position and semantics. // // The audited gap (Low): the FORCE_HTTPS redirect middleware was mounted BELOW // the dashboard-assistant router and POST /api/captcha/verify, so with dual // HTTP/HTTPS listeners and FORCE_HTTPS enabled, a plaintext request to those // two surfaces was served over plaintext (the redirect never ran for them — // the route registrations precede it in Express's source-order dispatch). // The fix relocates the mount to immediately BEFORE the dashboard-assistant // router mount; internals (condition, 301 status, Location construction) are // byte-identical — only placement changed. // // Locked in here: // 1. Behavioral, flag enabled + plaintext request (req.secure false): // GET /api/dashboard-assistant/*, POST /api/captcha/verify and // POST /login each answer 301 to the https same-path and NEVER reach // their handlers (the gap surfaces are covered; POST /login coverage is // preserved by the relocation). // 2. Behavioral, flag enabled + secure request (trusted loopback peer + // X-Forwarded-Proto: https, mirroring TRUST_PROXY=loopback): every // surface passes through to its handler — no redirect on https traffic. // 3. Behavioral, flag disabled / https listener absent: NO redirect // anywhere — the default (FORCE_HTTPS unset) is byte-unchanged, and an // HTTP-only deployment still serves every surface directly. // 4. Source pins: the FORCE_HTTPS mount appears BEFORE the // dashboard-assistant router mount AND before the POST /api/captcha/verify // registration in index.js, so a future mount reorder cannot silently // reopen the gap; it remains AFTER the session middleware and the // remote-proxy trust gate (order sanity for the landed gate stack), and // POST /login stays below it (still covered). The middleware body // (condition + redirect statement) and the REDIRECT_ALLOWED_HOSTS block // are pinned byte-identical and exactly once, moved together. // // Technique: the behavioral cases evaluate the REAL middleware statement and // the REAL REDIRECT_ALLOWED_HOSTS block sliced out of index.js (byte-identical // source, not a re-typed copy) in a vm sandbox with injected fixture globals — // same technique as tests/webhook-dispatch-hardening.test.js — then mount the // captured middleware on a real express app in production order (redirect → // dashboard-assistant router → captcha/verify → /login) and speak real HTTP. const test = require("node:test"); const assert = require("node:assert"); const fs = require("node:fs"); const path = require("node:path"); const vm = require("node:vm"); const http = require("node:http"); const express = require("express"); const ROOT = path.join(__dirname, ".."); const INDEX_JS = path.join(ROOT, "index.js"); const indexSource = fs.readFileSync(INDEX_JS, "utf8"); const { extractHostnameFromHeader } = require(path.join(ROOT, "utils", "origin-host.js")); const CONDITION_MARKER = "if (httpsAvailable && FORCE_HTTPS && !req.secure) {"; const REDIRECT_STATEMENT = "return res.redirect(301, `https://${hostname}${portSegment}${req.originalUrl}`);"; const REDIRECT_HOSTS_MARKER = "const REDIRECT_ALLOWED_HOSTS = new Set("; const DA_MOUNT_MARKER = 'app.use("/api/dashboard-assistant", createDashboardAssistantRouter({'; const CAPTCHA_MARKER = 'app.post("/api/captcha/verify"'; const LOGIN_MARKER = 'app.post("/login"'; const SESSION_MARKER = "app.use(sessionMiddleware);"; const TRUST_GATE_MARKER = "createRemoteProxyTrustGate({ enabled"; // Slices the shipped `app.use((req, res, next) => { ... });` statement that // contains the FORCE_HTTPS condition, byte-identical from index.js source. function sliceForceHttpsMount(source) { const condIdx = source.indexOf(CONDITION_MARKER); assert.ok(condIdx > 0, "FORCE_HTTPS condition not found in index.js"); const startMarker = "app.use((req, res, next) => {"; const start = source.lastIndexOf(startMarker, condIdx); assert.ok(start > 0, "FORCE_HTTPS app.use statement start not found"); const bodyOpen = source.indexOf("{", start); let depth = 0; let end = -1; for (let i = bodyOpen; i < source.length; i += 1) { if (source[i] === "{") depth += 1; else if (source[i] === "}") { depth -= 1; if (depth === 0) { end = i + 1; break; } } } assert.ok(end > 0, "unbalanced braces in FORCE_HTTPS middleware body"); assert.strictEqual(source.slice(end, end + 2), ");", "FORCE_HTTPS statement does not end with );"); return source.slice(start, end + 2); } // Slices the shipped `const REDIRECT_ALLOWED_HOSTS = new Set(...);` statement // (paren-delimited — the Set literal contains no braces). function sliceRedirectHostsStatement(source) { const start = source.indexOf(REDIRECT_HOSTS_MARKER); assert.ok(start > 0, "REDIRECT_ALLOWED_HOSTS declaration not found in index.js"); let depth = 0; let end = -1; for (let i = start + REDIRECT_HOSTS_MARKER.length - 1; i < source.length; i += 1) { if (source[i] === "(") depth += 1; else if (source[i] === ")") { depth -= 1; if (depth === 0) { end = i + 1; break; } } } assert.ok(end > 0, "unbalanced parens in REDIRECT_ALLOWED_HOSTS declaration"); assert.strictEqual(source[end], ";", "REDIRECT_ALLOWED_HOSTS statement does not end with ;"); return source.slice(start, end + 1); } const forceHttpsMountSource = sliceForceHttpsMount(indexSource); const redirectHostsSource = sliceRedirectHostsStatement(indexSource); // Evaluates the shipped statements in a fresh sandbox with fixture globals and // returns the captured middleware function (shipped code, not a copy). function evalForceHttpsMiddleware({ forceHttps, httpsAvailable, host, httpsPort, allowedHosts }) { const captured = []; const sandbox = { app: { use(fn) { captured.push(fn); } }, extractHostnameFromHeader, httpsAvailable, FORCE_HTTPS: forceHttps, HOST: host, HTTPS_PORT: httpsPort, process: { env: { REDIRECT_ALLOWED_HOSTS: allowedHosts || "" } }, }; const context = vm.createContext(sandbox); vm.runInContext(redirectHostsSource, context, { filename: "index.js#redirect-allowed-hosts" }); vm.runInContext(forceHttpsMountSource, context, { filename: "index.js#force-https-mount" }); assert.strictEqual(captured.length, 1, "middleware was not captured from the shipped statement"); return captured[0]; } // Boots a real express app in production registration order (redirect → // dashboard-assistant router → captcha/verify → /login) with probe handlers. function bootFixtureApp(middleware, { trustProxy } = {}) { const app = express(); app.set("trust proxy", trustProxy || "loopback"); const served = { dashboardAssistant: 0, captcha: 0, login: 0 }; const dashboardAssistantRouter = express.Router(); dashboardAssistantRouter.get("/status", (req, res) => { served.dashboardAssistant += 1; res.status(200).json({ ok: true, surface: "dashboard-assistant" }); }); app.use(middleware); app.use("/api/dashboard-assistant", dashboardAssistantRouter); app.post("/api/captcha/verify", (req, res) => { served.captcha += 1; res.status(200).json({ ok: true, surface: "captcha" }); }); app.post("/login", (req, res) => { served.login += 1; res.status(200).json({ ok: true, surface: "login" }); }); return { app, served }; } function requestAgainst(server, { method = "GET", localPath = "/", headers = {} }) { return new Promise((resolve, reject) => { const port = server.address().port; const req = http.request( { host: "127.0.0.1", port, method, path: localPath, headers: { host: `127.0.0.1:${port}`, ...headers }, }, (res) => { const chunks = []; res.on("error", reject); // house rule: error listener on every upstream response res.on("data", (c) => chunks.push(c)); res.on("end", () => resolve({ status: res.statusCode, location: res.headers.location || "", body: Buffer.concat(chunks).toString("utf8"), })); } ); req.on("error", reject); req.end(); }); } function listen(app) { return new Promise((resolve) => { const server = app.listen(0, "127.0.0.1", () => resolve(server)); }); } const FIXTURE_HOST = "panel.example"; const BASE_CONFIG = { forceHttps: true, httpsAvailable: true, host: FIXTURE_HOST, httpsPort: 443 }; test("force-https-coverage: flag enabled + plaintext — gap surfaces redirect before their handlers", async () => { const middleware = evalForceHttpsMiddleware(BASE_CONFIG); const { app, served } = bootFixtureApp(middleware); const server = await listen(app); try { const captcha = await requestAgainst(server, { method: "POST", localPath: "/api/captcha/verify" }); assert.strictEqual(captcha.status, 301); assert.strictEqual(captcha.location, `https://${FIXTURE_HOST}/api/captcha/verify`); assert.strictEqual(served.captcha, 0, "captcha/verify handler must not run over plaintext"); const da = await requestAgainst(server, { localPath: "/api/dashboard-assistant/status" }); assert.strictEqual(da.status, 301); assert.strictEqual(da.location, `https://${FIXTURE_HOST}/api/dashboard-assistant/status`); assert.strictEqual(served.dashboardAssistant, 0, "dashboard-assistant router must not run over plaintext"); const login = await requestAgainst(server, { method: "POST", localPath: "/login" }); assert.strictEqual(login.status, 301); assert.strictEqual(login.location, `https://${FIXTURE_HOST}/login`); assert.strictEqual(served.login, 0, "login handler must not run over plaintext (preserved behavior)"); } finally { await new Promise((r) => server.close(r)); } }); test("force-https-coverage: flag enabled + secure request (trusted loopback peer + XFP https) — pass-through everywhere", async () => { const middleware = evalForceHttpsMiddleware(BASE_CONFIG); const { app, served } = bootFixtureApp(middleware); const server = await listen(app); try { const secureHeaders = { "x-forwarded-proto": "https" }; const captcha = await requestAgainst(server, { method: "POST", localPath: "/api/captcha/verify", headers: secureHeaders }); assert.strictEqual(captcha.status, 200, "secure captcha/verify request must not redirect"); const da = await requestAgainst(server, { localPath: "/api/dashboard-assistant/status", headers: secureHeaders }); assert.strictEqual(da.status, 200, "secure dashboard-assistant request must not redirect"); const login = await requestAgainst(server, { method: "POST", localPath: "/login", headers: secureHeaders }); assert.strictEqual(login.status, 200, "secure login request must not redirect"); assert.deepStrictEqual(served, { dashboardAssistant: 1, captcha: 1, login: 1 }); } finally { await new Promise((r) => server.close(r)); } }); test("force-https-coverage: flag disabled — no redirect anywhere (default unchanged)", async () => { const middleware = evalForceHttpsMiddleware({ ...BASE_CONFIG, forceHttps: false }); const { app, served } = bootFixtureApp(middleware); const server = await listen(app); try { const captcha = await requestAgainst(server, { method: "POST", localPath: "/api/captcha/verify" }); const da = await requestAgainst(server, { localPath: "/api/dashboard-assistant/status" }); const login = await requestAgainst(server, { method: "POST", localPath: "/login" }); assert.strictEqual(captcha.status, 200); assert.strictEqual(da.status, 200); assert.strictEqual(login.status, 200); assert.deepStrictEqual(served, { dashboardAssistant: 1, captcha: 1, login: 1 }); } finally { await new Promise((r) => server.close(r)); } }); test("force-https-coverage: flag enabled but no https listener (httpsAvailable=false) — no redirect anywhere", async () => { const middleware = evalForceHttpsMiddleware({ ...BASE_CONFIG, httpsAvailable: false }); const { app, served } = bootFixtureApp(middleware); const server = await listen(app); try { const captcha = await requestAgainst(server, { method: "POST", localPath: "/api/captcha/verify" }); const da = await requestAgainst(server, { localPath: "/api/dashboard-assistant/status" }); const login = await requestAgainst(server, { method: "POST", localPath: "/login" }); assert.strictEqual(captcha.status, 200); assert.strictEqual(da.status, 200); assert.strictEqual(login.status, 200); assert.deepStrictEqual(served, { dashboardAssistant: 1, captcha: 1, login: 1 }); } finally { await new Promise((r) => server.close(r)); } }); test("force-https-coverage: source pins — mount precedes the gap surfaces, stays after session/trust-gate, body byte-identical", () => { const mwPos = indexSource.indexOf(CONDITION_MARKER); const daPos = indexSource.indexOf(DA_MOUNT_MARKER); const captchaPos = indexSource.indexOf(CAPTCHA_MARKER); const loginPos = indexSource.indexOf(LOGIN_MARKER); const sessionPos = indexSource.indexOf(SESSION_MARKER); const gatePos = indexSource.indexOf(TRUST_GATE_MARKER); const hostsPos = indexSource.indexOf(REDIRECT_HOSTS_MARKER); assert.ok(mwPos > 0, "FORCE_HTTPS condition missing from index.js"); assert.ok(daPos > 0, "dashboard-assistant mount missing from index.js"); assert.ok(captchaPos > 0, "captcha/verify registration missing from index.js"); assert.ok(loginPos > 0, "login registration missing from index.js"); // adpanel:force-https-coverage — the redirect mount must precede both gap // surfaces; a future reorder that puts it below them reopens the plaintext // coverage gap and must fail this pin. assert.ok(mwPos < daPos, "FORCE_HTTPS mount must precede the dashboard-assistant router mount"); assert.ok(mwPos < captchaPos, "FORCE_HTTPS mount must precede POST /api/captcha/verify"); // Order sanity vs landed stack: session/secure-pin stack and the remote-proxy // trust gate stay ABOVE the redirect mount. assert.ok(sessionPos > 0 && sessionPos < mwPos, "session middleware must precede the FORCE_HTTPS mount"); assert.ok(gatePos > 0 && gatePos < mwPos, "remote-proxy trust gate must precede the FORCE_HTTPS mount"); // POST /login stays below the mount — still covered by the redirect. assert.ok(loginPos > mwPos, "POST /login must remain below the FORCE_HTTPS mount (covered)"); // The relocated const travels with the mount, before it, exactly once. assert.ok(hostsPos > 0 && hostsPos < mwPos, "REDIRECT_ALLOWED_HOSTS must be declared before the FORCE_HTTPS mount"); assert.strictEqual(indexSource.split(CONDITION_MARKER).length - 1, 1, "FORCE_HTTPS condition must appear exactly once"); assert.strictEqual(indexSource.split(REDIRECT_STATEMENT).length - 1, 1, "redirect statement must appear exactly once"); assert.ok(forceHttpsMountSource.includes(REDIRECT_STATEMENT), "sliced middleware must contain the pinned redirect statement"); assert.strictEqual(indexSource.split(REDIRECT_HOSTS_MARKER).length - 1, 1, "REDIRECT_ALLOWED_HOSTS declaration must appear exactly once"); });