Files
Kelx/tests/stealth-asset-decoded-match.test.js
2026-11-30 16:32:37 +00:00

312 lines
16 KiB
JavaScript

"use strict";
// adpanel:stealth-asset-decoded-match — behavior + source pins for the
// stealth asset-gate encoded-spelling bypass.
//
// express.static (send 0.19.0) percent-decodes the request path exactly once
// before serving, but the stealth gate classified the RAW still-encoded
// req.path against STEALTH_ASSET_PATHS. A pre-gate probe could therefore
// request an encoded spelling of a covered asset (`/js/%63dn-fallback.js`)
// that evades the exact-match set (gate → next()) while the static wrapper
// decodes it and serves the real file — a 200 that fingerprints ADPanel while
// stealth is active. The repo's own rule at servePublicStatic/safeDecodePath
// ("authorization ... decisions must classify the DECODED path or encoded
// spellings of a path diverge from the resource actually served") now covers
// the gate too: isStealthProtectedAssetPath classifies safeDecodePath(path).
//
// These pins hold:
// 1. source: the classification consumes safeDecodePath, which is a hoisted
// function declaration doing ONE decodeURIComponent with a pass-through
// catch (no double decode — a double decode would false-match literal
// %-named paths send can never serve);
// 2. behavior: encoded spellings of set paths and of the /auth-assets/
// prefix classify PROTECTED after the fix, plain spellings are
// unchanged, and a double-encoded (%2563) spelling does NOT match —
// exactly mirroring what send serves (200 for single-encoded, literal-
// name 404 for double-encoded);
// 3. framework contract, exercised against the installed express + send:
// express.static serves the single-encoded spelling and 404s the
// double-encoded one, and the express router matches routes on the RAW
// pathname — which is why the login-path classification
// (isStealthProtectedLoginPath) needs no decode: an encoded spelling
// (`/%6Cogin`) never reaches the /login route handler, so there is no
// divergence for it to classify wrongly.
const test = require("node:test");
const assert = require("node:assert");
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
const http = require("node:http");
const ROOT = path.join(__dirname, "..");
const INDEX_JS = path.join(ROOT, "index.js");
const indexSource = fs.readFileSync(INDEX_JS, "utf8");
function indexOfOrThrow(needle, from = 0) {
const idx = indexSource.indexOf(needle, from);
assert.ok(idx >= 0, `expected source pin not found: ${needle}`);
return idx;
}
// Extraction pattern (same technique as stealth-returnto-backslash.test.js):
// stitch the set, the helper, and safeDecodePath into one evaluatable scope.
// safeDecodePath is a top-level function declaration in index.js (CommonJS),
// so it is hoisted to module scope and the earlier-defined helper may call it
// at request time — the stitched evaluation reproduces exactly that binding.
// index.js binds require("path") at module top (the helper composes send's
// normalize); new Function bodies see no module scope, so the same module
// object is handed in as a parameter — the identical binding.
function loadStealthAssetClassifier() {
const setStart = indexOfOrThrow("const STEALTH_ASSET_PATHS = new Set([");
const setEnd = indexSource.indexOf("]);", setStart);
assert.ok(setEnd > setStart, "STEALTH_ASSET_PATHS slice must be bounded");
const fnStart = indexOfOrThrow("function isStealthProtectedAssetPath(");
const fnEnd = indexOfOrThrow("function isStealthProtectedLoginPath(", fnStart);
assert.ok(fnEnd > fnStart, "isStealthProtectedAssetPath slice must be bounded");
const decodeStart = indexOfOrThrow("function safeDecodePath(p)");
const decodeEnd = indexOfOrThrow("function servePublicStatic(", decodeStart);
assert.ok(decodeEnd > decodeStart, "safeDecodePath slice must be bounded");
// The prefix-cover leg (adpanel:stealth-prefix-cover) references the shared
// PRE_AUTH_STATIC_PREFIXES const — defined later in index.js, evaluated at
// request time. The stitched scope must carry the same binding.
const prefixStart = indexOfOrThrow("const PRE_AUTH_STATIC_PREFIXES = [");
const prefixEnd = indexSource.indexOf("];", prefixStart);
assert.ok(prefixEnd > prefixStart, "PRE_AUTH_STATIC_PREFIXES slice must be bounded");
const extensionStart = indexOfOrThrow("const PRE_AUTH_STATIC_EXT = ");
const extensionEnd = indexOfOrThrow("\n", extensionStart);
const src =
indexSource.slice(setStart, setEnd + 3) + "\n" +
indexSource.slice(prefixStart, prefixEnd + 2) + "\n" +
indexSource.slice(extensionStart, extensionEnd) + "\n" +
indexSource.slice(fnStart, fnEnd) + "\n" +
indexSource.slice(decodeStart, decodeEnd);
return new Function(
"path",
`${src}\nreturn { isStealthProtectedAssetPath, safeDecodePath, STEALTH_ASSET_PATHS };`
)(path);
}
test("source: the asset classification runs on the DECODED path via safeDecodePath", () => {
const fnStart = indexOfOrThrow("function isStealthProtectedAssetPath(");
const fnEnd = indexOfOrThrow("function isStealthProtectedLoginPath(", fnStart);
const fnSrc = indexSource.slice(fnStart, fnEnd);
assert.ok(
fnSrc.includes("const decoded = safeDecodePath(String(pathname || \"\").trim());"),
"isStealthProtectedAssetPath must classify safeDecodePath(path) — the raw " +
"spelling lets /js/%63dn-fallback.js evade the exact-match set while send " +
"serves the decoded file"
);
assert.ok(
fnSrc.includes('path.posix.normalize("." + "/" + decoded)'),
"the decoded path must be normalized with send's exact composition " +
"normalize('.' + sep + path) — send normalizes AFTER decoding, so " +
"duplicate-slash/dot-segment spellings normalize onto covered paths and " +
"must classify protected (adpanel:stealth-asset-normalized-match)"
);
assert.ok(
fnSrc.includes('const p = "/" + sendNormalized;'),
"send's normalized intermediate is RELATIVE ('favicon.ico', not " +
"'/favicon.ico'); the absolute form send joins onto root is '/' + it"
);
assert.ok(
fnSrc.includes("/(?:^|[\\\\/])\\.\\.(?:[\\\\/]|$)/.test(sendNormalized)"),
"send 403s surviving '..' segments (UP_PATH_REGEXP) BEFORE joining root; " +
"the gate must classify those UNPROTECTED or a root-escaping spelling " +
"that clamps back onto a covered path (/../favicon.ico) becomes a decoy " +
"404 oracle beside send's swallowed-403 fallthrough"
);
assert.ok(
fnSrc.includes("adpanel:stealth-asset-decoded-match"),
"the decoded-match constraint must be documented at the classification"
);
assert.ok(
fnSrc.includes("adpanel:stealth-asset-normalized-match"),
"the normalized-match constraint must be documented at the classification"
);
});
test("source: safeDecodePath is a hoisted function declaration with a single decode", () => {
// Hoisting safety: the consumer (isStealthProtectedAssetPath) is textually
// earlier in index.js than safeDecodePath, so safeDecodePath MUST stay a
// function declaration (hoisted to module scope) — a `const` binding would
// be in TDZ only during module evaluation, but a function-expression or
// arrow `const` would still break any request-time call made before the
// declaration line is evaluated; pin the declaration form outright.
assert.ok(
indexSource.includes("function safeDecodePath(p)"),
"safeDecodePath must remain a hoisted function declaration"
);
assert.ok(
!indexSource.includes("const safeDecodePath"),
"safeDecodePath must not be re-bound as a const (hoisting + one-true-home)"
);
const decodeStart = indexOfOrThrow("function safeDecodePath(p)");
const decodeEnd = indexOfOrThrow("function servePublicStatic(", decodeStart);
const decodeSrc = indexSource.slice(decodeStart, decodeEnd);
const decodeCalls = decodeSrc.match(/decodeURIComponent/g) || [];
assert.strictEqual(
decodeCalls.length, 1,
"safeDecodePath must decode exactly once — send decodes once; a second " +
"decode would false-match literal %-named paths send can never serve"
);
assert.ok(
decodeSrc.includes("try { return decodeURIComponent(raw); } catch { return raw; }"),
"malformed sequences must pass through unchanged (send 400s them downstream)"
);
});
test("behavior: encoded spellings of covered assets classify PROTECTED after the fix", () => {
const { isStealthProtectedAssetPath, safeDecodePath } = loadStealthAssetClassifier();
// The evasion spellings from the verified finding, one per leg of the set.
const encodedSpellings = [
"/js/%63dn-fallback.js", // → /js/cdn-fallback.js
"/%6Cogin.css", // → /login.css
"/vendor/%66ontawesome/css/all.min.css", // → /vendor/fontawesome/css/all.min.css
"/images/%61dpanel-dark.svg", // → /images/adpanel-dark.svg
"/%66avicon.ico", // → /favicon.ico
"/branding-media/%6Cogin-background", // → /branding-media/login-background
"/branding-media/%6Cogo", // → /branding-media/logo (adpanel:branding-media-stealth-cover)
// An encoded spelling of the prefix decodes onto the same prefix leg.
"/auth-%61ssets/logo", // → /auth-assets/logo
];
for (const spelling of encodedSpellings) {
assert.strictEqual(
safeDecodePath(spelling),
decodeURIComponent(spelling),
`single decode must equal the spelling send serves: ${spelling}`
);
assert.strictEqual(
isStealthProtectedAssetPath(spelling), true,
`encoded spelling must classify PROTECTED: ${spelling}`
);
}
});
test("behavior: plain spellings are unchanged (decode is identity on non-encoded paths)", () => {
const { isStealthProtectedAssetPath, safeDecodePath, STEALTH_ASSET_PATHS } = loadStealthAssetClassifier();
for (const p of STEALTH_ASSET_PATHS) {
assert.strictEqual(
safeDecodePath(p), p,
`decode must be identity on the plain set entry: ${p}`
);
assert.strictEqual(isStealthProtectedAssetPath(p), true, p);
}
assert.strictEqual(isStealthProtectedAssetPath("/auth-assets/logo"), true, "prefix leg unchanged");
assert.strictEqual(isStealthProtectedAssetPath("/auth-assets/favicon"), false, "favicon exclusion unchanged");
assert.strictEqual(isStealthProtectedAssetPath("/dashboard"), false, "non-asset stays unprotected");
assert.strictEqual(isStealthProtectedAssetPath(""), false);
assert.strictEqual(isStealthProtectedAssetPath(null), false);
});
test("behavior: double-encoded spellings do NOT match the exact set (single-decode semantics mirror send)", () => {
const { isStealthProtectedAssetPath, safeDecodePath, STEALTH_ASSET_PATHS } = loadStealthAssetClassifier();
// %2563 decodes ONCE to the literal string "%63dn-fallback.js" — no set
// entry contains a "%", so this misses the exact-match set, exactly
// matching send, which looks up the literal "%63..." filename and 404s
// (verified behaviorally below). A double decode here would FALSE-MATCH
// the set leg. adpanel:stealth-prefix-cover: the spelling still classifies
// PROTECTED because its single-decoded form sits under the /js/ static
// prefix — the prefix decoy is uniform there (send 404s the literal name;
// no content either way), so this pin moved from the no-set-match class to
// the prefix-cover class without changing the no-leak contract.
assert.strictEqual(safeDecodePath("/js/%2563dn-fallback.js"), "/js/%63dn-fallback.js");
assert.strictEqual(isStealthProtectedAssetPath("/js/%2563dn-fallback.js"), true, "single-decoded form is under the /js/ prefix leg — uniform decoy");
assert.strictEqual(safeDecodePath("/%2566avicon.ico"), "/%66avicon.ico");
assert.strictEqual(STEALTH_ASSET_PATHS.has("/%66avicon.ico"), false, "the literal filename does not match the exact set");
assert.strictEqual(isStealthProtectedAssetPath("/%2566avicon.ico"), true, "the root extension rule still gives the literal filename a uniform decoy");
// A malformed sequence passes through unchanged (send 400s/404s it
// downstream); under a static prefix it takes the uniform decoy like every
// other prefix spelling.
assert.strictEqual(safeDecodePath("/js/%zzdn-fallback.js"), "/js/%zzdn-fallback.js");
assert.strictEqual(isStealthProtectedAssetPath("/js/%zzdn-fallback.js"), true, "malformed sequence still sits under the /js/ prefix leg");
});
test("behavioral: express.static serves the single-encoded spelling and 404s the double-encoded one — what the gate now classifies", async () => {
// The framework contract the fix relies on, exercised against the
// installed express + send with raw request lines (no URL normalization).
const express = require("express");
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "adpanel-stealth-assets-"));
try {
fs.mkdirSync(path.join(dir, "js"), { recursive: true });
fs.mkdirSync(path.join(dir, "vendor", "fontawesome", "css"), { recursive: true });
fs.writeFileSync(path.join(dir, "js", "cdn-fallback.js"), "FALLBACK-CONTENT");
fs.writeFileSync(path.join(dir, "login.css"), "LOGINCSS");
fs.writeFileSync(path.join(dir, "vendor", "fontawesome", "css", "all.min.css"), "FACSS");
const app = express();
app.use(express.static(dir));
const server = app.listen(0, "127.0.0.1");
await new Promise((resolve) => server.once("listening", resolve));
try {
const port = server.address().port;
const rawGet = (requestPath) => new Promise((resolve, reject) => {
const req = http.get({ host: "127.0.0.1", port, path: requestPath }, (res) => {
let body = "";
res.on("data", (c) => (body += c));
res.on("end", () => resolve({ status: res.statusCode, body }));
});
req.on("error", reject);
});
// send percent-decodes once: the single-encoded spelling is served —
// the pre-gate 200 that fingerprinted ADPanel.
const single = await rawGet("/js/%63dn-fallback.js");
assert.strictEqual(single.status, 200);
assert.strictEqual(single.body, "FALLBACK-CONTENT");
const facss = await rawGet("/vendor/%66ontawesome/css/all.min.css");
assert.strictEqual(facss.status, 200);
const plainCss = await rawGet("/%6Cogin.css");
assert.strictEqual(plainCss.status, 200);
assert.strictEqual(plainCss.body, "LOGINCSS");
// ...and does NOT double-decode: the double-encoded spelling 404s on
// the literal "%63..." filename — matching the gate's unprotected
// classification of that spelling (no false match).
const double = await rawGet("/js/%2563dn-fallback.js");
assert.strictEqual(double.status, 404);
} finally {
server.close();
}
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
test("behavioral: the express router matches routes on the RAW pathname (login paths need no decode)", async () => {
// isStealthProtectedLoginPath classifies the raw path against the same
// literals the router matches routes on — express does NOT decode before
// route matching, so an encoded spelling (/%6Cogin) never reaches the
// /login handler and no encoded-spelling divergence exists for it.
const express = require("express");
const app = express();
let loginHits = 0;
app.get("/login", (req, res) => { loginHits += 1; res.send("LOGIN-ROUTE"); });
app.use((req, res) => res.status(404).send("NO-ROUTE"));
const server = app.listen(0, "127.0.0.1");
await new Promise((resolve) => server.once("listening", resolve));
try {
const port = server.address().port;
const rawGet = (requestPath) => new Promise((resolve, reject) => {
const req = http.get({ host: "127.0.0.1", port, path: requestPath }, (res) => {
let body = "";
res.on("data", (c) => (body += c));
res.on("end", () => resolve({ status: res.statusCode, body }));
});
req.on("error", reject);
});
const plain = await rawGet("/login");
assert.strictEqual(plain.status, 200);
assert.strictEqual(plain.body, "LOGIN-ROUTE");
assert.strictEqual(loginHits, 1);
const encoded = await rawGet("/%6Cogin");
assert.strictEqual(encoded.status, 404, "encoded spelling must not reach the /login route");
assert.strictEqual(encoded.body, "NO-ROUTE");
assert.strictEqual(loginHits, 1, "the /login handler must never fire for the encoded spelling");
} finally {
server.close();
}
});