Initial upload to Gitea

This commit is contained in:
antonn committed 2026-11-30 16:32:37 +00:00
1 parent 78193254ad
commit 8478998cae
1485 files changed
+461025 -42348

No files matched your search

+496
View File
@@ -0,0 +1,496 @@
"use strict";
// Tests for the config-integrity fix (Vuln 2): the three database config
// loaders previously failed OPEN — a torn (crash-truncated) JSON file was
// swallowed by a catch-all into "nothing configured" (and, for
// loadDatabaseConfig, CACHED as such), so the next read-modify-write cycle
// persisted the empty state and erased every tracked user entry while the
// accounts stayed live on the server with known passwords — the exact
// "unseeable and unrevokable credential" outcome the drop taxonomy forbids.
//
// Contract locked here:
// - Missing file → the historical default shape ({enabled:false,...}),
// still cached by loadDatabaseConfig under its 30s TTL.
// - Existing file that cannot be read/used (read error, 0-byte/whitespace
// torn-write artifact, invalid/truncated JSON, non-object JSON) → the
// loader THROWS with code DATABASE_CONFIG_CORRUPT / MONGODB_CONFIG_CORRUPT
// / PGADMIN_CONFIG_CORRUPT, logs loudly, names the exact file, tells the
// admin the file was NOT auto-reset and must be restored from backup or
// removed manually — and nothing about the corrupt state is cached.
// - The passwordHash scrub (database) and the plaintext→bcrypt migration
// (mongodb) survive, and their rewrites — like every save — go through
// utils/atomic-file's temp+fsync+rename primitive: no torn files, mode
// 0600 enforced exactly, no .tmp litter left behind.
//
// index.js boots servers on require, so the config pipeline is sliced out of
// the source and evaluated in a vm sandbox (same technique as
// webhook-config-write-lock.test.js): the slices run the REAL atomic-file
// primitive (and real bcrypt for the mongo migration) against a real fs
// inside a temp directory via __dirname.
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 vm = require("node:vm");
const INDEX_JS = path.join(__dirname, "..", "index.js");
const ATOMIC_FILE_JS = path.join(__dirname, "..", "utils", "atomic-file.js");
const REAL_BCRYPT = require("bcrypt");
function endIndexOfFunction(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}`);
}
// Builds a vm-sandboxed module for one loader region. The shared corruption
// error builder (dbConfigCorruptionError) is prepended when the region does
// not already contain it. require() is shimmed to the real atomic-file
// primitive and real bcrypt; everything else in the region runs against a
// real fs rooted at a fresh temp dir.
function buildDbConfigModule({ startMarker, endMarker, constName, fileName, needsCacheConsts, loadConfigName, saveConfigName, fsOverride }) {
const source = fs.readFileSync(INDEX_JS, "utf8");
const helperStart = source.indexOf("function dbConfigCorruptionError");
assert.ok(helperStart >= 0, "dbConfigCorruptionError helper must exist");
const helper = source.slice(helperStart, endIndexOfFunction(source, "function dbConfigCorruptionError"));
const regionStart = source.indexOf(startMarker);
assert.ok(regionStart >= 0, `region marker ${startMarker} not found`);
const region = source.slice(regionStart, endIndexOfFunction(source, endMarker));
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "adpanel-db-config-"));
const exposed = { tmpDir, errors: [], logs: [] };
const sandbox = {
fs: fsOverride || fs,
path,
process,
BCRYPT_ROUNDS: 4,
__dirname: tmpDir,
[constName]: path.join(tmpDir, fileName),
console: {
log: (...a) => exposed.logs.push(a.join(" ")),
warn: () => {},
debug: () => {},
info: () => {},
error: (...a) => exposed.errors.push(a.join(" ")),
},
require: (name) => {
if (name === "./utils/atomic-file") return require(ATOMIC_FILE_JS);
if (name === "bcrypt") return REAL_BCRYPT;
throw new Error(`test sandbox: unexpected require(${name})`);
},
__exports: (obj) => Object.assign(exposed, obj),
};
const prelude = needsCacheConsts
? "let _dbConfigCache = null; let _dbConfigCacheTs = 0; const DB_CONFIG_CACHE_TTL_MS = 30000;\n"
: "";
const context = vm.createContext(sandbox);
vm.runInContext(
`${prelude}${helper}\n${region}\n;__exports({ loadConfig: ${loadConfigName}, saveConfig: ${saveConfigName} });`,
context,
{ filename: "db-config-slice.js" }
);
exposed.configPath = path.join(tmpDir, fileName);
return exposed;
}
function buildDatabaseModule() {
return buildDbConfigModule({
startMarker: "function loadDatabaseConfig(options = {})",
endMarker: "function saveDatabaseConfig",
constName: "DATABASE_CONFIG_FILE",
fileName: "database-config.json",
// The cache consts sit just above loadDatabaseConfig in index.js but the
// slice starts at the function, so provide them here verbatim.
needsCacheConsts: true,
loadConfigName: "loadDatabaseConfig",
saveConfigName: "saveDatabaseConfig",
});
}
function buildMongoModule() {
return buildDbConfigModule({
startMarker: "const MONGODB_CONFIG_FILE",
endMarker: "function saveMongoDBConfig",
constName: "MONGODB_CONFIG_FILE",
fileName: "mongodb-config.json",
needsCacheConsts: false,
loadConfigName: "loadMongoDBConfig",
saveConfigName: "saveMongoDBConfig",
});
}
function buildPgAdminModule() {
return buildDbConfigModule({
startMarker: "const PGADMIN_CONFIG_FILE",
endMarker: "function savePgAdminConfig",
constName: "PGADMIN_CONFIG_FILE",
fileName: "pgadmin-config.json",
needsCacheConsts: false,
loadConfigName: "loadPgAdminConfig",
saveConfigName: "savePgAdminConfig",
});
}
function withModule(mod, fn) {
try {
fn(mod);
} finally {
fs.rmSync(mod.tmpDir, { recursive: true, force: true });
}
}
const VALID_DB_CONFIG = {
enabled: true,
config: { type: "mysql", host: "127.0.0.1", port: 3306 },
users: [{ username: "admin", createdAt: 1 }],
};
// ─── loadDatabaseConfig / saveDatabaseConfig ─────────────────────────────────
test("database: missing file returns the default shape, and that default is served from the 30s cache", () => {
withModule(buildDatabaseModule(), (mod) => {
const first = mod.loadConfig();
// Objects built inside the vm realm carry a different Object prototype,
// so structural compares go through a JSON round-trip.
assert.deepStrictEqual(JSON.parse(JSON.stringify(first)), { enabled: false, config: null, users: [] });
// A valid config lands on disk after the default was cached: the cached
// default must still be served until the TTL expires (proves the default
// really takes the cache path), while a fresh load bypasses it.
fs.writeFileSync(mod.configPath, JSON.stringify(VALID_DB_CONFIG), "utf8");
assert.deepStrictEqual(
JSON.parse(JSON.stringify(mod.loadConfig())),
{ enabled: false, config: null, users: [] },
"the cached default must be served within the TTL"
);
assert.equal(mod.loadConfig({ fresh: true }).enabled, true, "a fresh load must bypass the cache and read the file");
});
});
test("database: corrupt JSON on disk THROWS DATABASE_CONFIG_CORRUPT naming the file, loudly logged, and nothing is cached", () => {
withModule(buildDatabaseModule(), (mod) => {
// Exactly what a crash mid-write leaves behind: a truncated object.
fs.writeFileSync(mod.configPath, '{"enabled":true,"config":{"type":"mysql","users":[{"username":"admin"', "utf8");
assert.throws(
() => mod.loadConfig(),
(err) => {
assert.equal(err.code, "DATABASE_CONFIG_CORRUPT");
assert.ok(err.message.includes(mod.configPath), "the message must name the exact file path");
assert.ok(/corrupt or truncated/.test(err.message), "the message must say the file is corrupt/truncated");
assert.ok(/NOT automatically reset/.test(err.message), "the message must say the file was not auto-reset");
assert.ok(/restore|remove/i.test(err.message), "the message must tell the admin how to recover");
assert.ok(/Underlying error:/.test(err.message), "the message must include the underlying error");
return true;
}
);
assert.ok(
mod.errors.some((l) => l.includes(mod.configPath) && /corrupt or truncated/.test(l)),
"the loader must console.error the corruption loudly"
);
// The corrupt state must NOT be cached: after repairing the file, the
// very next (cached-path) load must see the repair.
fs.writeFileSync(mod.configPath, JSON.stringify(VALID_DB_CONFIG), "utf8");
assert.equal(mod.loadConfig().enabled, true, "a repaired file must load immediately — no corrupt default may linger in the cache");
});
});
test("database: an empty (0-byte) file is a torn-write artifact and fails closed the same way", () => {
withModule(buildDatabaseModule(), (mod) => {
fs.writeFileSync(mod.configPath, "", "utf8");
assert.throws(
() => mod.loadConfig({ fresh: true }),
(err) => err.code === "DATABASE_CONFIG_CORRUPT" && err.message.includes(mod.configPath)
);
});
});
test("database: a whitespace-only file fails closed the same way", () => {
withModule(buildDatabaseModule(), (mod) => {
fs.writeFileSync(mod.configPath, " \n\t ", "utf8");
assert.throws(
() => mod.loadConfig({ fresh: true }),
(err) => err.code === "DATABASE_CONFIG_CORRUPT" && err.message.includes(mod.configPath)
);
});
});
test("database: a valid file round-trips through save → load, lands 0600, parses on disk, and leaves no .tmp litter", () => {
withModule(buildDatabaseModule(), (mod) => {
assert.equal(mod.saveConfig(VALID_DB_CONFIG), true, "the save must report success");
const onDisk = JSON.parse(fs.readFileSync(mod.configPath, "utf8"));
assert.deepStrictEqual(onDisk, VALID_DB_CONFIG, "the file must be complete and parseable");
assert.equal(fs.statSync(mod.configPath).mode & 0o777, 0o600, "the file must be 0600 exactly (enforced via fchmod, umask-proof)");
assert.ok(!fs.readdirSync(mod.tmpDir).some((f) => f.endsWith(".tmp")), "the atomic write must leave no temp litter");
const loaded = JSON.parse(JSON.stringify(mod.loadConfig({ fresh: true })));
assert.deepStrictEqual(
loaded,
{ enabled: true, config: VALID_DB_CONFIG.config, users: VALID_DB_CONFIG.users },
"the load must return the normalized saved state"
);
});
});
test("database: the legacy passwordHash scrub still runs and its rewrite is atomic (file parses, no entry lost)", () => {
withModule(buildDatabaseModule(), (mod) => {
const legacy = {
enabled: true,
config: { type: "mysql", host: "127.0.0.1", port: 3306 },
users: [{ username: "admin", passwordHash: "deadbeef", createdAt: 1 }, { username: "app", createdAt: 2 }],
};
fs.writeFileSync(mod.configPath, JSON.stringify(legacy), "utf8");
const loaded = mod.loadConfig({ fresh: true });
assert.ok(
loaded.users.every((u) => !Object.prototype.hasOwnProperty.call(u, "passwordHash")),
"passwordHash must be stripped from the in-memory result"
);
// The rewrite replaces the file wholesale via rename: it must parse and
// contain every surviving field.
const onDisk = JSON.parse(fs.readFileSync(mod.configPath, "utf8"));
assert.ok(onDisk.users.every((u) => !Object.prototype.hasOwnProperty.call(u, "passwordHash")), "passwordHash must be scrubbed on disk");
assert.equal(onDisk.users.length, 2, "the scrub rewrite must keep every user entry");
assert.equal(onDisk.enabled, true, "the scrub rewrite must keep the rest of the config");
assert.ok(!fs.readdirSync(mod.tmpDir).some((f) => f.endsWith(".tmp")), "the scrub rewrite must be atomic (no litter)");
});
});
// ─── loadMongoDBConfig / saveMongoDBConfig ───────────────────────────────────
test("mongodb: missing file returns the default shape", () => {
withModule(buildMongoModule(), (mod) => {
assert.deepStrictEqual(JSON.parse(JSON.stringify(mod.loadConfig())), { enabled: false, users: [] });
});
});
test("mongodb: corrupt JSON THROWS MONGODB_CONFIG_CORRUPT naming the file, loudly logged", () => {
withModule(buildMongoModule(), (mod) => {
fs.writeFileSync(mod.configPath, '{"enabled":true,"users":[{"username":"adm', "utf8");
assert.throws(
() => mod.loadConfig(),
(err) => {
assert.equal(err.code, "MONGODB_CONFIG_CORRUPT");
assert.ok(err.message.includes(mod.configPath));
assert.ok(/NOT automatically reset/.test(err.message));
return true;
}
);
assert.ok(mod.errors.some((l) => l.includes(mod.configPath)), "the loader must log the corruption loudly");
});
});
test("mongodb: an empty file fails closed the same way", () => {
withModule(buildMongoModule(), (mod) => {
fs.writeFileSync(mod.configPath, "", "utf8");
assert.throws(() => mod.loadConfig(), (err) => err.code === "MONGODB_CONFIG_CORRUPT" && err.message.includes(mod.configPath));
});
});
test("mongodb: legacy plaintext users still migrate to bcrypt and the migration persists atomically", () => {
withModule(buildMongoModule(), (mod) => {
const legacy = { enabled: true, host: "127.0.0.1", port: "27017", users: [{ username: "admin", password: "sup3rsecret" }] };
fs.writeFileSync(mod.configPath, JSON.stringify(legacy), "utf8");
const loaded = mod.loadConfig();
const admin = loaded.users[0];
assert.ok(!admin.password, "the plaintext password must be removed from the in-memory config");
assert.ok(typeof admin.passwordHash === "string" && admin.passwordHash.startsWith("$2"), "a bcrypt hash must take its place");
assert.ok(REAL_BCRYPT.compareSync("sup3rsecret", admin.passwordHash), "the hash must verify against the original password");
const onDisk = JSON.parse(fs.readFileSync(mod.configPath, "utf8"));
assert.ok(!JSON.stringify(onDisk).includes("sup3rsecret"), "the plaintext must be gone from disk");
assert.ok(onDisk.users[0].passwordHash.startsWith("$2"), "the migrated hash must be persisted");
assert.equal(onDisk.enabled, true, "the migration must keep the rest of the config");
assert.ok(!fs.readdirSync(mod.tmpDir).some((f) => f.endsWith(".tmp")), "the migration rewrite must be atomic (no litter)");
});
});
test("mongodb: save round-trips atomically with 0600 and no tmp litter", () => {
withModule(buildMongoModule(), (mod) => {
const data = { enabled: true, host: "127.0.0.1", port: "27017", users: [{ username: "admin", passwordHash: "$2a$04$hash" }] };
assert.equal(mod.saveConfig(data), true);
assert.deepStrictEqual(JSON.parse(fs.readFileSync(mod.configPath, "utf8")), data);
assert.equal(fs.statSync(mod.configPath).mode & 0o777, 0o600);
assert.ok(!fs.readdirSync(mod.tmpDir).some((f) => f.endsWith(".tmp")));
});
});
// ─── loadPgAdminConfig / savePgAdminConfig ───────────────────────────────────
test("pgadmin: missing file returns the default shape", () => {
withModule(buildPgAdminModule(), (mod) => {
assert.deepStrictEqual(JSON.parse(JSON.stringify(mod.loadConfig())), { enabled: false, users: [] });
});
});
test("pgadmin: corrupt JSON THROWS PGADMIN_CONFIG_CORRUPT naming the file, loudly logged", () => {
withModule(buildPgAdminModule(), (mod) => {
fs.writeFileSync(mod.configPath, '{"enabled":true,"users":[{"email":"a@b.c"', "utf8");
assert.throws(
() => mod.loadConfig(),
(err) => {
assert.equal(err.code, "PGADMIN_CONFIG_CORRUPT");
assert.ok(err.message.includes(mod.configPath));
assert.ok(/NOT automatically reset/.test(err.message));
return true;
}
);
assert.ok(mod.errors.some((l) => l.includes(mod.configPath)), "the loader must log the corruption loudly");
});
});
test("pgadmin: an empty file fails closed the same way", () => {
withModule(buildPgAdminModule(), (mod) => {
fs.writeFileSync(mod.configPath, "", "utf8");
assert.throws(() => mod.loadConfig(), (err) => err.code === "PGADMIN_CONFIG_CORRUPT" && err.message.includes(mod.configPath));
});
});
test("pgadmin: save round-trips atomically with 0600 and no tmp litter", () => {
withModule(buildPgAdminModule(), (mod) => {
const data = { enabled: true, host: "127.0.0.1", port: "5432", users: [{ email: "a@b.c", createdAt: 1 }], bootstrapAuth: { email: "enc:v1:x", password: "enc:v1:y" } };
assert.equal(mod.saveConfig(data), true);
assert.deepStrictEqual(JSON.parse(fs.readFileSync(mod.configPath, "utf8")), data);
assert.equal(fs.statSync(mod.configPath).mode & 0o777, 0o600, "the pre-existing 0600 mode must be preserved");
assert.ok(!fs.readdirSync(mod.tmpDir).some((f) => f.endsWith(".tmp")));
});
});
// ─── Source-level guarantees ─────────────────────────────────────────────────
test("source: all three config writers go through the atomic primitive, never in-place writeFileSync", () => {
const source = fs.readFileSync(INDEX_JS, "utf8");
for (const [fn, marker] of [
["saveDatabaseConfig", "function saveDatabaseConfig"],
["savePgAdminConfig", "function savePgAdminConfig"],
["saveMongoDBConfig", "function saveMongoDBConfig"],
]) {
const body = source.slice(source.indexOf(marker), endIndexOfFunction(source, marker));
assert.ok(body.includes('require("./utils/atomic-file").atomicWriteFileSync'), `${fn} must write via the atomic primitive`);
assert.ok(!body.includes("fs.writeFileSync"), `${fn} must not write in place`);
}
// The two in-loader migration rewrites must be atomic too. The loader
// regions are bounded by the NEXT function's marker: brace-matching from
// "function loadDatabaseConfig" would stop at the `= {}` default in its
// signature.
const dbLoad = source.slice(source.indexOf("function loadDatabaseConfig"), source.indexOf("function saveDatabaseConfig"));
assert.ok(dbLoad.includes('require("./utils/atomic-file").atomicWriteFileSync'), "the passwordHash scrub rewrite must be atomic");
assert.ok(!dbLoad.includes("fs.writeFileSync"), "loadDatabaseConfig must not rewrite in place");
const mongoLoad = source.slice(source.indexOf("function loadMongoDBConfig"), source.indexOf("function saveMongoDBConfig"));
assert.ok(mongoLoad.includes('require("./utils/atomic-file").atomicWriteFileSync'), "the plaintext→bcrypt migration rewrite must be atomic");
assert.ok(!mongoLoad.includes("fs.writeFileSync"), "loadMongoDBConfig must not rewrite in place");
// The loaders fail closed: the corruption codes must exist and the old
// catch-all-default structure must be gone.
assert.ok(source.includes('"DATABASE_CONFIG_CORRUPT"'), "database loader must raise DATABASE_CONFIG_CORRUPT");
assert.ok(source.includes('"MONGODB_CONFIG_CORRUPT"'), "mongo loader must raise MONGODB_CONFIG_CORRUPT");
assert.ok(source.includes('"PGADMIN_CONFIG_CORRUPT"'), "pgadmin loader must raise PGADMIN_CONFIG_CORRUPT");
});
// ─── Non-object JSON payloads (reviewer test gap) ────────────────────────────
// Valid JSON that parses to a non-object (array, string, number, null) must
// fail closed with the *_CONFIG_CORRUPT code like any other unusable file —
// previously `null` read as the fail-open default and pgadmin returned the
// garbage verbatim, letting untyped TypeErrors escape into route handlers.
test("database: JSON that parses to a non-object (array/string/number/null) fails closed", () => {
for (const payload of ["[1,2]", '"42"', "42", "null"]) {
withModule(buildDatabaseModule(), (mod) => {
fs.writeFileSync(mod.configPath, payload, "utf8");
assert.throws(
() => mod.loadConfig(),
(err) => err.code === "DATABASE_CONFIG_CORRUPT" && /not a config object/.test(err.message),
`payload ${payload} must fail closed`
);
});
}
});
test("mongodb: JSON that parses to a non-object fails closed", () => {
for (const payload of ["[1,2]", '"42"', "42", "null"]) {
withModule(buildMongoModule(), (mod) => {
fs.writeFileSync(mod.configPath, payload, "utf8");
assert.throws(
() => mod.loadConfig(),
(err) => err.code === "MONGODB_CONFIG_CORRUPT" && /not a config object/.test(err.message),
`payload ${payload} must fail closed`
);
});
}
});
test("pgadmin: JSON that parses to a non-object fails closed", () => {
for (const payload of ["[1,2]", '"42"', "42", "null"]) {
withModule(buildPgAdminModule(), (mod) => {
fs.writeFileSync(mod.configPath, payload, "utf8");
assert.throws(
() => mod.loadConfig(),
(err) => err.code === "PGADMIN_CONFIG_CORRUPT" && /not a config object/.test(err.message),
`payload ${payload} must fail closed`
);
});
}
});
// ─── ENOENT race (file vanishes between existsSync and readFileSync) ─────────
// The loaders probe existence with existsSync and then read; a manual admin
// deletion in between makes readFileSync throw ENOENT. That is the missing-
// file state, not corruption: it must yield the same default as a genuine
// absence, not a misleading *_CONFIG_CORRUPT.
function buildEnoentOverride() {
const enoent = new Error("ENOENT race (simulated)");
enoent.code = "ENOENT";
return {
existsSync: () => true,
readFileSync: () => { throw enoent; },
};
}
test("database: ENOENT between existsSync and read is the missing-file state, not corruption", () => {
withModule(buildDatabaseModule({ fsOverride: buildEnoentOverride() }), (mod) => {
const result = JSON.parse(JSON.stringify(mod.loadConfig()));
assert.deepEqual(result, { enabled: false, config: null, users: [] });
assert.ok(mod.errors.length === 0, "no corruption error may be logged for a vanished file");
// The default must be cached exactly like a genuine absence (30s TTL).
const cached = JSON.parse(JSON.stringify(mod.loadConfig()));
assert.deepEqual(cached, { enabled: false, config: null, users: [] });
});
});
test("mongodb: ENOENT between existsSync and read is the missing-file state, not corruption", () => {
withModule(buildMongoModule({ fsOverride: buildEnoentOverride() }), (mod) => {
const result = JSON.parse(JSON.stringify(mod.loadConfig()));
assert.deepEqual(result, { enabled: false, users: [] });
assert.ok(mod.errors.length === 0, "no corruption error may be logged for a vanished file");
});
});
test("pgadmin: ENOENT between existsSync and read is the missing-file state, not corruption", () => {
withModule(buildPgAdminModule({ fsOverride: buildEnoentOverride() }), (mod) => {
const result = JSON.parse(JSON.stringify(mod.loadConfig()));
assert.deepEqual(result, { enabled: false, users: [] });
assert.ok(mod.errors.length === 0, "no corruption error may be logged for a vanished file");
});
});