"use strict"; // Tests for the template-store sync memory bounds (audit finding: "sync // buffers the ENTIRE upstream file tree into memory before the signature // gate — no cap on file count or total bytes"). // // The per-file cap (TEMPLATE_STORE_FILE_MAX_BYTES) bounds one fetch, but the // SET was unbounded: a compromised upstream repo (the exact adversary the // Ed25519 signature gate exists for) could declare tens of thousands of // max-sized files, and every panel would buffer gigabytes (raw bytes + a // re-serialized pretty JSON copy per file) BEFORE verification — OOM kill, // restart boot-loop, and admin store GETs wedged on the sync promise. // The remediation under test: // 1. evaluateTemplateStoreListingLimits() — a pure pre-flight check on the // listing (file count + worst-case declared bytes, unknown sizes billed // at the per-file cap) run BEFORE any byte is fetched. // 2. In-fetch enforcement: the sync also accumulates the bytes actually // buffered (listings can lie about sizes) and aborts the WHOLE sync on // breach — a breach must not be swallowed by the per-file try/catch. // Both fail closed: the throw is caught by the sync's own catch, which // records the error and leaves the previous cache/manifest untouched. // // index.js boots servers on require, so the store constants, the limits // helper and syncTemplateStoreCache are sliced out of the source and // evaluated in a vm sandbox (same technique as // template-store-local-override.test.js / runtime-process-command.test.js). 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 INDEX_JS = path.join(__dirname, "..", "index.js"); function endIndexOfFunction(source, startMarker) { const start = source.indexOf(startMarker); assert.ok(start >= 0, `marker ${startMarker} not found in index.js`); 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 buildSyncCode() { const source = fs.readFileSync(INDEX_JS, "utf8"); // The size-limit constants (the env-overridable trio), then the pure // listing-limits helper, then the sync function itself. const constStart = source.indexOf("const TEMPLATE_STORE_FILE_MAX_BYTES"); assert.ok(constStart >= 0, "template store size constants not found"); const constEnd = source.indexOf("// Template images (installer AND runtime)"); assert.ok(constEnd > constStart, "size constants block boundary not found"); const helperStart = source.indexOf("function evaluateTemplateStoreListingLimits"); assert.ok(helperStart > constEnd, "listing-limits helper not found"); const helperEnd = endIndexOfFunction(source, "function evaluateTemplateStoreListingLimits"); const syncEnd = endIndexOfFunction(source, "async function syncTemplateStoreCache"); const syncStart = source.indexOf("async function syncTemplateStoreCache"); // Module-level state the sync function closes over in index.js. const prelude = [ "let templateStoreSyncPromise = null;", 'let templateStoreLastSyncError = "";', 'let templateStoreLastSyncWarning = "";', ].join("\n"); return [ source.slice(constStart, constEnd), source.slice(helperStart, helperEnd), prelude, source.slice(syncStart, syncEnd), ].join("\n"); } const SYNC_CODE = buildSyncCode(); // A fresh sandbox per scenario: its own env (so the caps vary per test) and // stubs for every free variable the sync body touches. Everything is a stub // that fails the test by default; a scenario overrides only what it needs. function buildSandbox(env = {}, stubs = {}) { const sandbox = { console: { log() { }, warn() { }, error() { } }, process: { env: { ...env } }, Buffer, crypto: require("node:crypto"), path, fsp: { mkdir: async () => { }, readFile: async () => { throw new Error("no manifest file in test"); }, }, TEMPLATE_STORE_CATEGORIES: [ { id: "games", label: "Games" }, { id: "communication", label: "Communication" }, { id: "development", label: "Development" }, { id: "hosting", label: "Hosting" }, { id: "media", label: "Media" }, ], TEMPLATE_STORE_CACHE_DIR: "/tmp/adpanel-sync-limits-test/cache", TEMPLATE_STORE_MANIFEST_FILE: "/tmp/adpanel-sync-limits-test/cache/manifest.json", TEMPLATE_STORE_REPO: "example/store", TEMPLATE_STORE_REF: "main", TEMPLATE_STORE_LOCAL_OVERRIDES_ENABLED: false, TEMPLATE_STORE_SYNC_INTERVAL_MS: 60 * 60 * 1000, // No pinned key + warn mode: the signature gate must never be what fires // in these tests — only the listing/budget limits under test. TEMPLATE_STORE_TRUST: { mode: "warn", key: null, keyPinned: false, autoUpdate: false }, readTemplateStoreManifest: async () => null, listTemplateStoreRemoteFiles: async () => ({ files: [], source: "github" }), fetchTemplateStoreFileRaw: async () => { throw new Error("fetch stub must not be reached"); }, verifyListedContentHash: () => ({ verified: true }), verifyStoreSignature: () => ({ verified: true, digest: "", generatedAt: "", reason: "" }), fetchTemplateStoreSignatureFile: async () => ({ signatureFile: null, warning: "" }), readTemplateStoreTrustState: async () => null, writeTemplateStoreTrustState: async () => { }, writeFileAtomic: async () => { }, readTemplateStoreLocalOverrides: async () => [], selectTemplateStoreLocalOverrideDisposition: () => ({ apply: false, reason: "test stub" }), pruneTemplateStoreCategory: async () => { }, buildStoreSyncDiff: () => ({}), normalizeTemplateDefinition: (template) => template, ...stubs, }; vm.createContext(sandbox); vm.runInContext(SYNC_CODE, sandbox); return sandbox; } function listingJson(count, size) { return JSON.stringify(Array.from({ length: count }, (_, i) => ({ categoryId: "games", fileName: `template-${i}.json`, relPath: `games/template-${i}.json`, hash: "", size, }))); } test("a listing above the file-count cap is rejected before a single fetch", async () => { const fetchCalls = []; const sandbox = buildSandbox({}, { listTemplateStoreRemoteFiles: async () => ({ files: JSON.parse(listingJson(501, 1)), source: "github" }), fetchTemplateStoreFileRaw: async (relPath) => { fetchCalls.push(relPath); return { raw: "{}", source: "github-raw", url: "" }; }, }); await assert.rejects( vm.runInContext("syncTemplateStoreCache('test')", sandbox), (err) => /listing rejected/.test(err.message) && /previous cache is kept/.test(err.message) ); assert.equal(fetchCalls.length, 0, "no file may be fetched from a hostile listing"); }); test("a listing with declared sizes summing over the byte cap is rejected", async () => { // Defaults: cap 64 MiB, per-file worst case 512 KiB. 129 * 512 KiB > 64 MiB // (the file count is fine, so the byte check is what fires). const sandbox = buildSandbox({}); const rejected = vm.runInContext(`evaluateTemplateStoreListingLimits(${listingJson(129, 512 * 1024)})`, sandbox); assert.equal(rejected.ok, false); assert.match(rejected.reason, /byte limit/); // Exactly at the cap is fine — the check is a strict > (128 * 512 KiB == 64 MiB). const atCap = vm.runInContext(`evaluateTemplateStoreListingLimits(${listingJson(128, 512 * 1024)})`, sandbox); assert.equal(atCap.ok, true, "a listing exactly at the byte cap must pass"); }); test("unknown/zero sizes are billed at the per-file worst case", () => { // Tight env: 1 MiB total (the floor), 32 KiB per-file (the floor). 33 // unknown-size files * 32 KiB = 1088 KiB > 1 MiB → reject; 32 files == // exactly 1 MiB → pass. const sandbox = buildSandbox({ ADPANEL_TEMPLATE_STORE_MAX_TOTAL_BYTES: String(1024 * 1024), ADPANEL_TEMPLATE_STORE_FILE_MAX_BYTES: String(32 * 1024), }); // size 0 (what normalizeTemplateStoreFlatFile stores for unknown), missing // and non-numeric sizes must all bill at the per-file worst case. for (const size of [0, undefined, "not-a-number"]) { const entries = JSON.stringify(Array.from({ length: 33 }, (_, i) => ({ size }))); const rejected = vm.runInContext(`evaluateTemplateStoreListingLimits(${entries})`, sandbox); assert.equal(rejected.ok, false, `size ${String(size)} must bill at the per-file worst case`); assert.match(rejected.reason, /byte limit/); } const atCap = vm.runInContext(`evaluateTemplateStoreListingLimits(${JSON.stringify(Array.from({ length: 32 }, () => ({ size: 0 })))})`, sandbox); assert.equal(atCap.ok, true); }); test("a normal listing within both caps passes", () => { const sandbox = buildSandbox({}); const ok = vm.runInContext(`evaluateTemplateStoreListingLimits(${listingJson(40, 20 * 1024)})`, sandbox); assert.deepEqual(ok, { ok: true, reason: "" }); // Boundary: exactly TEMPLATE_STORE_MAX_FILES entries passes. const atFileCap = vm.runInContext(`evaluateTemplateStoreListingLimits(${listingJson(500, 1)})`, sandbox); assert.equal(atFileCap.ok, true, "a listing exactly at the file cap must pass"); // Defensive: null/undefined listings behave as empty. assert.equal(vm.runInContext("evaluateTemplateStoreListingLimits(null).ok", sandbox), true); assert.equal(vm.runInContext("evaluateTemplateStoreListingLimits(undefined).ok", sandbox), true); }); test("env overrides adjust both caps", () => { const sandbox = buildSandbox({ ADPANEL_TEMPLATE_STORE_MAX_FILES: "5" }); const rejected = vm.runInContext(`evaluateTemplateStoreListingLimits(${listingJson(6, 1)})`, sandbox); assert.equal(rejected.ok, false); assert.match(rejected.reason, /6 store files, above the 5 file limit/); // An unparseable env value falls back to the default (500), not to 0/NaN. const fallback = buildSandbox({ ADPANEL_TEMPLATE_STORE_MAX_FILES: "garbage" }); assert.equal(vm.runInContext(`evaluateTemplateStoreListingLimits(${listingJson(500, 1)}).ok`, fallback), true); assert.equal(vm.runInContext(`evaluateTemplateStoreListingLimits(${listingJson(501, 1)}).ok`, fallback), false); }); test("a listing that lies about sizes aborts the whole sync mid-fetch and keeps the previous cache", async () => { // Two files declaring 10 bytes each pass the pre-flight, but the fetch // returns ~600 KiB per file (raw + pretty copy ≈ 1.2 MiB buffered), over // the 1 MiB budget. The breach must surface as a sync failure, not be // swallowed by the per-file catch — otherwise the hostile set would sail // into the signature gate buffered in memory. const written = []; const sandbox = buildSandbox( { ADPANEL_TEMPLATE_STORE_MAX_TOTAL_BYTES: String(1024 * 1024) }, { listTemplateStoreRemoteFiles: async () => ({ files: JSON.parse(listingJson(2, 10)), source: "github" }), fetchTemplateStoreFileRaw: async () => { const payload = JSON.stringify({ id: "t", pad: "y".repeat(300 * 1024) }); return { raw: payload, source: "github-raw", url: "" }; }, writeFileAtomic: async (targetPath, content) => { written.push({ targetPath, content }); }, } ); await assert.rejects( vm.runInContext("syncTemplateStoreCache('test')", sandbox), /bytes buffered, above the .* byte limit/ ); assert.equal(written.length, 0, "a breached sync must promote nothing — the previous cache is kept"); }); test("the fetch loop re-enforces the budget and never swallows a breach", () => { const source = fs.readFileSync(INDEX_JS, "utf8"); const syncSource = source.slice( source.indexOf("async function syncTemplateStoreCache"), endIndexOfFunction(source, "async function syncTemplateStoreCache") ); // The pre-flight guard runs after the listing and before any fetch. const listingIdx = syncSource.indexOf("listTemplateStoreRemoteFiles()"); const gateIdx = syncSource.indexOf("evaluateTemplateStoreListingLimits(remote.files)"); const fetchIdx = syncSource.indexOf("fetchTemplateStoreFileRaw("); assert.ok(listingIdx > -1, "sync fetches the remote listing"); assert.ok(gateIdx > listingIdx, "the listing-limits check runs after the listing"); assert.ok(gateIdx < fetchIdx, "the listing-limits check runs before the first file fetch"); assert.ok(syncSource.includes("template store listing rejected:"), "a rejected listing throws with a clear message"); assert.ok(syncSource.includes("the previous cache is kept"), "the rejection message promises the previous cache is kept"); // In-fetch accounting covers BOTH retained copies (raw string + pretty // re-serialization) and is compared against the total-byte cap. const accIdx = syncSource.indexOf("bufferedBytes += Buffer.byteLength(fetched.raw) + Buffer.byteLength(prettyRaw);"); assert.ok(accIdx > -1, "the loop accumulates actually-buffered bytes (raw + pretty)"); const capIdx = syncSource.indexOf("bufferedBytes > TEMPLATE_STORE_MAX_TOTAL_BYTES"); assert.ok(capIdx > accIdx, "the running total is compared against the cap after accumulation"); // The breach rethrow must precede the per-file swallow, and the per-file // catch must still be there for ordinary per-file failures. const rethrowIdx = syncSource.indexOf("if (err === budgetAbort) throw err;"); const swallowIdx = syncSource.indexOf('console.warn(`[template-store] Failed to cache'); assert.ok(rethrowIdx > -1, "the budget breach is rethrown out of the per-file catch"); assert.ok(rethrowIdx < swallowIdx, "the rethrow guard runs before the per-file warn-and-continue"); // The budget-abort error is created inside the try (so the catch guard can // identify it) and carries the fail-closed message. const abortIdx = syncSource.indexOf("budgetAbort = new Error("); assert.ok(abortIdx > -1 && abortIdx < rethrowIdx, "the abort error is assigned before the catch guard uses it"); assert.ok(syncSource.includes("the previous cache is kept`"), "the abort message promises the previous cache is kept"); });