"use strict"; // adpanel:cookie-secure-trusted-proto — pins for the widened auto leg of // cookieSecureForRequest (index.js). // // The audited divergence: the auto leg keyed on Express's TRUST_PROXY view // only (`connection.encrypted || req.secure`, default loopback), while the // login gate's predicate (isRemoteProxyTrustViolationRequest) uses the wider // peer-trust view (TRUSTED_PROXY_IPS + XFP via getTrustedForwardedProto / // getDirectRemoteIp / isTrustedProxyIp). With TRUSTED_PROXY_IPS set and // TRUST_PROXY forgotten, POST /login passes the gate (the proxy IS trusted // in the peer-trust view) while cookies shipped WITHOUT Secure // (req.secure false) — and the runtime misconfig warn is structurally blind, // because a trusted peer is exactly the state that never fires the // predicate: the half-fixed setup was silently the worst state for cookie // flags. // // Contract locked here: // - The auto leg now ALSO treats the request as secure when // getTrustedForwardedProto(req) === "https" — the ONE peer-trust // resolver the gate uses, no second XFP parse inside the predicate. // - The widened leg can only ever ADD the Secure attribute: the consumer // census at the bottom proves NO consumer gates/refuses on // cookieSecureForRequest (every site is a `secure:` cookie attribute, a // clearCookie attribute match, the db-proxy cookie-attr plumbing, or // the upgrade-only Secure pin — pin-when-true). A refusal gate on this // predicate would be a design regression and must fail loudly here. // - The explicit-env leg keeps priority and is unchanged: // SESSION_COOKIE_SECURE=true pins Secure on every request (even for a // non-trusted peer); =false keeps cookies non-Secure even for a // trusted-proxy https request (the operator's explicit choice, and the // reason the boot advisory still names the pin as an override). // - The express-session secure:"auto" mirror legs are byte-identical: // direct TLS (connection.encrypted) and req.secure (TRUST_PROXY) keep // their pre-fix behavior. // - The boot advisory says exactly which half each env fixes // (TRUSTED_PROXY_IPS: throttle bucket + cookie Secure; // TRUST_PROXY: the Express req.secure view / FORCE_HTTPS redirect) and // carries the half-fixed note (the runtime warn cannot fire when the // peer is trusted — the widened leg is the compensation). 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 net = require("node:net"); const session = require("express-session"); const { createLoginSessionBinder } = require("../utils/login-session-bind"); const { createCredentialSessionRebinder } = require("../utils/credential-session-rebind"); const { createTrustedSessionFactory } = require("../utils/session-middleware"); const ROOT = path.join(__dirname, ".."); const INDEX_JS = path.join(ROOT, "index.js"); const indexSource = fs.readFileSync(INDEX_JS, "utf8"); function endIndexOfBlock(source, startMarker) { const start = source.indexOf(startMarker); assert.ok(start >= 0, `marker ${startMarker} not found`); const bodyStart = source.indexOf("{", start); let depth = 0; for (let i = bodyStart; i < source.length; i += 1) { if (source[i] === "{") depth += 1; else if (source[i] === "}") { depth -= 1; if (depth === 0) return i + 1; } } assert.fail(`unbalanced braces after marker ${startMarker}`); } function sliceBlock(source, startMarker) { const start = source.indexOf(startMarker); assert.ok(start >= 0, `marker ${startMarker} not found`); return source.slice(start, endIndexOfBlock(source, startMarker)); } // --------------------------------------------------------------------------- // Behavioral: the REAL function + the REAL peer-trust helper chain under vm // (same extraction shape as tests/remote-proxy-misconfig-warning.test.js). // --------------------------------------------------------------------------- function buildCookieSecure({ trustedProxyIpsEnv = "", secureExplicit = false, secureValue = false } = {}) { const helpers = indexSource.slice( indexSource.indexOf("const TRUSTED_PROXY_IPS = new Set("), endIndexOfBlock(indexSource, "function getTrustedForwardedProto(req)") ); const fnSource = sliceBlock(indexSource, "function cookieSecureForRequest(req)"); const context = vm.createContext({ net: require("node:net"), process: { env: { TRUSTED_PROXY_IPS: trustedProxyIpsEnv } }, }); vm.runInContext([ `const SESSION_COOKIE_SECURE_EXPLICIT = ${JSON.stringify(secureExplicit)};`, `const SESSION_COOKIE_SECURE = ${JSON.stringify(secureValue)};`, helpers, fnSource, ].join("\n"), context, { filename: "index.js#cookie-secure" }); assert.strictEqual(typeof context.cookieSecureForRequest, "function", "cookieSecureForRequest extraction failed"); assert.strictEqual(typeof context.getTrustedForwardedProto, "function", "the peer-trust resolver must be extracted alongside the predicate"); return context.cookieSecureForRequest; } // Plain-HTTP request shape at the node: no direct TLS, Express not trusting // the peer (TRUST_PROXY unset/loopback), headers as given. function plainHttpReq(headers, remoteAddress) { return { secure: false, connection: { remoteAddress }, socket: { remoteAddress }, headers: headers || {}, }; } test("THE FIX: XFP https from a TRUSTED_PROXY_IPS peer yields Secure in auto mode (TRUST_PROXY irrelevant)", () => { const fn = buildCookieSecure({ trustedProxyIpsEnv: "10.8.0.5, 192.0.2.9" }); assert.equal( fn(plainHttpReq({ "x-forwarded-proto": "https" }, "10.8.0.5")), true, "the half-fixed setup (TRUSTED_PROXY_IPS set, TRUST_PROXY forgotten) must now ship Secure cookies" ); assert.equal( fn(plainHttpReq({ "x-forwarded-proto": "https" }, "192.0.2.9")), true, "every listed peer counts, not just the first entry" ); }); test("loopback peer reporting https is trusted in the peer-trust view (no XFP trust inflation)", () => { const fn = buildCookieSecure({}); assert.equal(fn(plainHttpReq({ "x-forwarded-proto": "https" }, "127.0.0.1")), true, "IPv4 loopback"); assert.equal(fn(plainHttpReq({ "x-forwarded-proto": "https" }, "::1")), true, "IPv6 loopback"); }); test("XFP https from an UNTRUSTED peer stays non-Secure — the widened leg adds no trust", () => { const fn = buildCookieSecure({}); assert.equal( fn(plainHttpReq({ "x-forwarded-proto": "https" }, "203.0.113.7")), false, "an attacker-forged XFP from a direct connection must not mint Secure cookies, same as before the fix" ); }); test("no https claim → false even for a trusted peer (the leg keys on the CLAIM, not the trust)", () => { const fn = buildCookieSecure({ trustedProxyIpsEnv: "10.8.0.5" }); assert.equal(fn(plainHttpReq({}, "10.8.0.5")), false, "no XFP header"); assert.equal(fn(plainHttpReq({ "x-forwarded-proto": "http" }, "10.8.0.5")), false, "explicit http claim"); }); test("the LAST XFP hop wins, matching getTrustedForwardedProto (and the login gate)", () => { const fn = buildCookieSecure({ trustedProxyIpsEnv: "10.8.0.5" }); assert.equal(fn(plainHttpReq({ "x-forwarded-proto": "https,http" }, "10.8.0.5")), false, "last hop http"); assert.equal(fn(plainHttpReq({ "x-forwarded-proto": "http,https" }, "10.8.0.5")), true, "last hop https"); }); test("the express-session secure:auto mirror legs are byte-identical (direct TLS / req.secure)", () => { const fn = buildCookieSecure({}); assert.equal(fn({ connection: { encrypted: true }, headers: {} }), true, "direct TLS"); assert.equal(fn({ secure: true, headers: {} }), true, "req.secure (TRUST_PROXY view)"); assert.equal(fn({ secure: false, headers: {} }), false, "plain HTTP, no claim"); assert.equal(fn(undefined), false, "no request at all"); assert.equal(fn(null), false); }); test("explicit SESSION_COOKIE_SECURE leg keeps priority, both directions, unchanged", () => { const pinnedTrue = buildCookieSecure({ secureExplicit: true, secureValue: true }); assert.equal(pinnedTrue(plainHttpReq({ "x-forwarded-proto": "https" }, "10.8.0.5")), true); assert.equal(pinnedTrue(plainHttpReq({}, "203.0.113.7")), true, "the pin ignores trust entirely"); const pinnedFalse = buildCookieSecure({ secureExplicit: true, secureValue: false }); assert.equal( pinnedFalse(plainHttpReq({ "x-forwarded-proto": "https" }, "10.8.0.5")), false, "the operator's explicit =false must NOT be overridden by the widened leg" ); }); test("IPv6-mapped peer is normalized before the trust check (same rule as the gate)", () => { const fn = buildCookieSecure({ trustedProxyIpsEnv: "10.8.0.5" }); assert.equal( fn(plainHttpReq({ "x-forwarded-proto": "https" }, "::ffff:10.8.0.5")), true, "mapped peer counts as trusted" ); }); // --------------------------------------------------------------------------- // Source pins: one home, no second parse, order of legs. // --------------------------------------------------------------------------- const cookieFn = sliceBlock(indexSource, "function cookieSecureForRequest(req)"); test("source: the widened leg uses the ONE resolver — no second XFP parse inside the predicate", () => { assert.ok( cookieFn.includes("getTrustedForwardedProto(req) === \"https\""), "the auto leg must consult the shared peer-trust resolver" ); assert.strictEqual( (cookieFn.match(/getTrustedForwardedProto/g) || []).length, 1, "exactly one resolver call inside the predicate" ); assert.ok( !cookieFn.includes("x-forwarded-proto") && !cookieFn.includes("remoteAddress"), "no second header/peer parse inside the predicate — the resolver is the one home" ); assert.strictEqual( (indexSource.match(/function getTrustedForwardedProto\(req\)/g) || []).length, 1, "getTrustedForwardedProto stays defined exactly once in index.js" ); }); test("source: explicit leg first, express-session mirror leg byte-identical", () => { const explicitAt = cookieFn.indexOf("if (SESSION_COOKIE_SECURE_EXPLICIT) return SESSION_COOKIE_SECURE;"); const autoAt = cookieFn.indexOf("(req.connection && req.connection.encrypted) || req.secure === true || getTrustedForwardedProto(req) === \"https\""); assert.ok(explicitAt > -1 && autoAt > explicitAt, "explicit-env leg keeps priority over the auto legs"); assert.ok( cookieFn.includes("(req.connection && req.connection.encrypted) || req.secure === true"), "the express-session secure:auto mirror substring is unchanged (pinned also by remote-proxy-misconfig-warning.test.js)" ); assert.ok( cookieFn.includes("if (SESSION_COOKIE_SECURE_EXPLICIT) return SESSION_COOKIE_SECURE;"), "the explicit leg is unchanged" ); }); test("source: the tag documents the fix at its sites", () => { assert.strictEqual( (indexSource.split("adpanel:cookie-secure-trusted-proto").length - 1), 3, "exactly three tagged sites: the predicate comment, the boot-advisory amendment, the in-function one-liner" ); assert.ok( indexSource.includes("Amendment (adpanel:cookie-secure-trusted-proto):"), "the boot advisory block carries the half-fixed note" ); assert.ok( indexSource.includes("the runtime warn cannot fire"), "the half-fixed note states the warn's structural blindness" ); }); test("source: boot advisory names which half each env fixes", () => { const AUTO_BLOCK_MARKER = "if (!SESSION_COOKIE_SECURE_EXPLICIT) {"; const autoBlock = sliceBlock(indexSource, AUTO_BLOCK_MARKER); const BOOT_ADVISORY_TEXT = "[config] SESSION_COOKIE_SECURE is auto: if TLS terminates at a REMOTE proxy (not loopback), add its IP to TRUSTED_PROXY_IPS"; assert.ok(autoBlock.includes('console.warn("' + BOOT_ADVISORY_TEXT), "the advisory console.warn stays inside the auto-mode block with its pinned prefix"); const advisory = autoBlock.slice(autoBlock.indexOf(BOOT_ADVISORY_TEXT)); assert.ok(advisory.includes("also restores Secure cookies without TRUST_PROXY"), "TRUSTED_PROXY_IPS alone fixes the cookie half now"); assert.ok(advisory.includes("FORCE_HTTPS redirect"), "TRUST_PROXY's half is the Express req.secure view incl. the redirect"); assert.ok(advisory.includes("TRUST_PROXY") && advisory.includes("SESSION_COOKIE_SECURE=true"), "all remedies still named"); assert.ok(advisory.includes("without Secure") && advisory.includes("one throttle bucket"), "both consequences still named"); assert.strictEqual( (indexSource.match(/SESSION_COOKIE_SECURE is auto: if TLS terminates/g) || []).length, 1, "the boot advisory text stays unique" ); assert.ok(!advisory.includes("SESSION_COOKIE_SECURE=true)"), "the advisory must not render the pin remedy as a parenthesized token (auto-block pin)"); }); // --------------------------------------------------------------------------- // Consumer census: NO consumer may gate/refuse on the predicate. // --------------------------------------------------------------------------- test("consumer census: cookieSecureForRequest never appears in a refusal/gate position", () => { const occurrences = []; let at = indexSource.indexOf("cookieSecureForRequest"); while (at > -1) { occurrences.push(at); at = indexSource.indexOf("cookieSecureForRequest", at + 1); } // The definition + the middleware call site + every cookie-attribute use. assert.ok(occurrences.length >= 2, "the predicate must exist and be used"); for (const at2 of occurrences) { const before = indexSource.slice(Math.max(0, at2 - 80), at2); const after = indexSource.slice(at2, at2 + 120); // Forbidden: any negated / compared-false / refusal-shaped use. (A // trimmed-before ending in "!" covers both !predicate and // `x !== predicate` gate shapes.) assert.ok(!before.trimEnd().endsWith("!"), `occurrence at ${at2}: a negated use (!cookieSecureForRequest) would gate/refuse on the predicate`); assert.ok(!after.startsWith("cookieSecureForRequest(req) === false"), `occurrence at ${at2}: a === false comparison would gate on the predicate`); assert.ok(!after.startsWith("cookieSecureForRequest(req) !== true"), `occurrence at ${at2}: a !== true comparison would gate on the predicate`); } // The ONLY `if`-guarded consumer is the upgrade-only Secure pin — and it // is pin-when-true (the widened leg makes the pin fire for trusted-proxy // https requests, exactly the desired durable upgrade). const pinGuard = "if (req.session?.cookie && req.session.cookie.secure !== true && cookieSecureForRequest(req) === true) {"; assert.ok(indexSource.includes(pinGuard), "the secure-pin middleware keeps its pin-when-true guard"); const pinCount = indexSource.split(pinGuard).length - 1; assert.strictEqual(pinCount, 1, "exactly one pin-when-true guard (the Secure-sync middleware)"); // No other if-guarded form exists. assert.ok(!indexSource.includes("if (cookieSecureForRequest("), "no consumer may branch directly on the predicate outside the pinned pin guard"); }); test("consumer census: the durable pin machinery is intact (the widened leg feeds a durable write)", () => { const middleware = sliceBlock(indexSource, "app.use((req, res, next) => {\n // adpanel:remote-proxy-misconfig-warning"); assert.ok(middleware.includes("req.session.cookie.secure = true;"), "the pin still flips the cookie"); assert.ok(middleware.includes("req.session.cookieSecurePinned = true;"), "the dirtying marker still accompanies the pin (adpanel:secure-pin-durable)"); }); test("trusted proxy Secure policy survives every session regeneration path and reaches Set-Cookie", async () => { const store = new session.MemoryStore(); const socket = new net.Socket(); Object.defineProperty(socket, "remoteAddress", { value: "192.0.2.9" }); const req = new http.IncomingMessage(socket); req.url = req.originalUrl = "/login"; req.method = "POST"; req.secure = false; req.headers = { "x-forwarded-proto": "https" }; const res = new http.ServerResponse(req); const secureForRequest = buildCookieSecure({ trustedProxyIpsEnv: "192.0.2.9" }); const middleware = createTrustedSessionFactory({ session, isRequestSecure: secureForRequest })({ store, secret: "synthetic-cookie-regression-secret-32-chars", name: "adpanel.sid", resave: false, saveUninitialized: false, rolling: true, cookie: { maxAge: 365 * 24 * 60 * 60 * 1000, secure: "auto", httpOnly: true, sameSite: "lax" }, }); const deps = { withTimeout: (promise) => promise, writeRevokedSidTombstone: async () => true, sessionCarriesProtectedPendingAuthState: () => false, getSessionDisplayId: () => "redacted", ensureRememberLoginSessionId: (request) => (request.session.rememberLoginId = "synthetic-remember-id"), buildBrowserSessionAuditFromRequest: () => ({}), setRememberLoginCookie: () => Date.now() + 60000, markRememberLoginSessionFresh: () => {}, upsertActiveBrowserSessionCacheEntry: () => {}, clearRememberLoginCookie: () => {}, revokeRememberLoginRegistryEntry: async () => true, }; const binder = createLoginSessionBinder(deps); const rebinder = createCredentialSessionRebinder({ ...deps, destroyBrowserSessionsForUser: async () => ({ destroyed: 1, rememberLoginsRevoked: 1, errors: [] }), }); try { await new Promise((resolve, reject) => middleware(req, res, (err) => err ? reject(err) : resolve())); assert.equal(secureForRequest(req), true, "the panel trusts this proxy's HTTPS claim"); assert.equal(req.secure, false, "the session-only transport view does not change the original request"); req.session.cookie.secure = true; req.session.cookieSecurePinned = true; await binder.bindLoginSession(req, res, { user: { id: 7, email: "owner@example.test", session_epoch: 19 } }); assert.equal(req.session.cookie.secure, true, "password and CAPTCHA completion share the protected binder"); const loginSid = req.sessionID; await rebinder.rebindOwnerSession(req, res, { user: { id: 7, email: "owner@example.test", session_epoch: 20 } }); assert.notEqual(req.sessionID, loginSid); assert.equal(req.session.cookie.secure, true, "credential changes also regenerate with the trusted Secure policy"); await new Promise((resolve, reject) => req.session.regenerate((err) => err ? reject(err) : resolve())); assert.equal(req.session.cookie.secure, true, "direct regeneration used by remember restoration inherits the same policy"); req.session.user = "owner@example.test"; res.writeHead(200); const sidCookie = (res.getHeader("set-cookie") || []).find((value) => value.startsWith("adpanel.sid=")); assert.ok(sidCookie, "a completed login must deliver its session cookie"); assert.match(sidCookie, /;\s*Secure(?:;|$)/i, "regeneration must not downgrade the trusted Secure policy"); assert.match(sidCookie, /;\s*HttpOnly(?:;|$)/i); assert.match(sidCookie, /;\s*SameSite=Lax(?:;|$)/i); } finally { socket.destroy(); } }); test("session cookie emission honors trusted transport and explicit policy without broad proxy trust", async () => { for (const scenario of [ { peer: "192.0.2.9", forwarded: "https", cookieSecure: "auto", expectedSecure: true, deliver: true }, { peer: "203.0.113.7", forwarded: "https", cookieSecure: "auto", expectedSecure: false, deliver: true }, { peer: "192.0.2.9", forwarded: "https,http", cookieSecure: "auto", expectedSecure: false, deliver: true }, { peer: "192.0.2.9", forwarded: "https", cookieSecure: false, expectedSecure: false, deliver: true }, { peer: "192.0.2.9", forwarded: "https", cookieSecure: true, expectedSecure: true, deliver: true }, { peer: "203.0.113.7", forwarded: "http", cookieSecure: true, expectedSecure: true, deliver: false }, ]) { const socket = new net.Socket(); Object.defineProperty(socket, "remoteAddress", { value: scenario.peer }); const req = new http.IncomingMessage(socket); req.url = req.originalUrl = "/login"; req.secure = false; req.headers = { "x-forwarded-proto": scenario.forwarded }; const res = new http.ServerResponse(req); const transport = buildCookieSecure({ trustedProxyIpsEnv: "192.0.2.9" }); const middleware = createTrustedSessionFactory({ session, isRequestSecure: transport })({ store: new session.MemoryStore(), secret: "synthetic-cookie-regression-secret-32-chars", name: "adpanel.sid", resave: false, saveUninitialized: false, cookie: { secure: scenario.cookieSecure, httpOnly: true, sameSite: "lax" }, }); try { await new Promise((resolve, reject) => middleware(req, res, (err) => err ? reject(err) : resolve())); await new Promise((resolve, reject) => req.session.regenerate((err) => err ? reject(err) : resolve())); req.session.user = "owner@example.test"; assert.equal(req.session.cookie.secure, scenario.expectedSecure); assert.equal(req.secure, false); res.writeHead(200); const cookies = res.getHeader("set-cookie") || []; assert.equal(cookies.length > 0, scenario.deliver, "explicit Secure on plain HTTP must not leak a cookie"); if (scenario.deliver) { assert.equal(/;\s*Secure(?:;|$)/i.test(cookies[0]), scenario.expectedSecure); } } finally { socket.destroy(); } } }); test("session transport factory is wired once and preserves the session-store API", () => { assert.equal(indexSource.split('require("./utils/session-middleware").createTrustedSessionFactory({ session: require("express-session"), isRequestSecure })').length - 1, 1); const factory = createTrustedSessionFactory({ session, isRequestSecure: () => false }); assert.equal(factory.Store, session.Store); assert.equal(factory.MemoryStore, session.MemoryStore); assert.throws(() => createTrustedSessionFactory({ session }), TypeError); });