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

+354
View File
@@ -0,0 +1,354 @@
"use strict";
// adpanel:totp-sealing-key-override — unit pins for the TOTP seed-sealing
// module's key-input override. The finding: the AES-256-GCM key that seals
// users.secret TOTP seeds was scrypt(SESSION_SECRET, fixed-salt) with no
// independent key env and no re-seal path, so rotating SESSION_SECRET
// permanently bricked 2FA for every enrolled user (sealed decrypt fails →
// fail-closed mass lockout). The fix adds TOTP_SEALING_KEY, mirroring the
// REMEMBER_LOGIN_SECRET override mechanics (env override || derived
// fallback), with ONE hard invariant the pins below lock:
//
// - Unset/empty override → the KDF input is process.env.SESSION_SECRET,
// BYTE-IDENTICAL to the pre-override algorithm (same scryptSync, same
// salt, same 32-byte length, same default params): every seal minted
// before this change stays decryptable. Proven by cross-decryption
// against an INDEPENDENTLY computed scrypt key — GCM tag verification
// only succeeds under the exact key bytes, so a successful authenticated
// open in BOTH directions is a key-equality proof, not a circumstantial
// one (a param drift — cost, salt, length — breaks the cross-open).
// - Set override → different key material; seal/unseal roundtrips succeed
// only under the same override.
// - NO fallback: a seal minted under one input can never be opened under
// the other (decryptTotpSecret returns null — the ledger-pinned
// fail-closed posture, untouched by this change). A wrong/rotated key
// must never fall back to any other derivation; a silent fallback would
// convert key rotation/tampering into a 2FA bypass.
// - Source pins: the boot check routes TOTP_SEALING_KEY through the ONE
// shared requireStrongSecretOverride helper beside its three siblings
// (same 32-char floor, real helper body driven in a sandbox), and the
// constraint comment exists at BOTH the boot-check call and the
// derivation site.
const test = require("node:test");
const assert = require("node:assert");
const crypto = require("node:crypto");
const fs = require("node:fs");
const path = require("node:path");
const vm = require("node:vm");
const { migratePlaintextTotpSecrets } = require("../services/totp-secret-migration");
const ROOT = path.join(__dirname, "..");
const MODULE_PATH = require.resolve("./totp-secret-crypto");
const INDEX_JS = path.join(ROOT, "index.js");
const MODULE_JS = path.join(ROOT, "utils", "totp-secret-crypto.js");
const ENC_PREFIX = "enc:v1:";
const SESSION_SECRET = "adpanel-totp-test-session-secret-0123456789abcdef";
const OVERRIDE = "totp-sealing-override-key-0123456789abcdef-zyxwvu";
const SEED = "JBSWY3DPEHPK3PXPJBSWY3DPEHPK3PXP";
test("legacy seed migration seals only the exact seed still stored and never changes its generation", async () => {
const secretCrypto = freshModule({ SESSION_SECRET });
const rawSeed = ` ${SEED} `;
const row = { id: 7, secret: rawSeed, session_epoch: 42 };
const written = [];
const db = {
pool: { query: async () => [[{ id: row.id, secret: row.secret }]] },
query: async (sql, params) => {
written.push({ sql, params });
assert.strictEqual(sql, "UPDATE users SET secret = ? WHERE id = ? AND BINARY secret = BINARY ?");
assert.strictEqual(params[2], rawSeed, "the CAS pins raw stored bytes, not the trimmed seed");
if (row.id !== params[1] || row.secret !== params[2]) return { affectedRows: 0 };
row.secret = params[0];
return { affectedRows: 1 };
},
};
const logger = { log() {}, warn() {}, debug() {} };
assert.strictEqual(await migratePlaintextTotpSecrets({ db, secretCrypto, logger }), 1);
assert.strictEqual(secretCrypto.decryptTotpSecret(row.secret), SEED);
assert.strictEqual(row.session_epoch, 42, "sealing the same factor does not revoke sessions");
assert.strictEqual(await migratePlaintextTotpSecrets({ db, secretCrypto, logger }), 0);
assert.strictEqual(written.length, 1, "an already sealed factor is never re-sealed");
const indexSource = fs.readFileSync(INDEX_JS, "utf8");
assert.match(indexSource, /await require\("\.\/services\/totp-secret-migration"\)\.migratePlaintextTotpSecrets\(\{ db \}\)/);
assert.doesNotMatch(indexSource, /UPDATE users SET secret = \? WHERE id = \?"/);
});
test("legacy seed migration loses to concurrent resets, rotations, and another sealing worker", async () => {
const secretCrypto = freshModule({ SESSION_SECRET });
for (const replacement of [null, secretCrypto.encryptTotpSecret("KRSXG5DSNFXGOIDB"), secretCrypto.encryptTotpSecret(SEED)]) {
const row = { id: 7, secret: SEED, session_epoch: 41 };
const db = {
pool: { query: async () => {
const snapshot = { id: row.id, secret: row.secret };
row.secret = replacement;
row.session_epoch = 42;
return [[snapshot]];
} },
query: async (sql, params) => {
assert.match(sql, /AND BINARY secret = BINARY \?/);
if (row.id !== params[1] || row.secret !== params[2]) return { affectedRows: 0 };
row.secret = params[0];
return { affectedRows: 1 };
},
};
const logs = [];
const logger = { log: (message) => logs.push(message), warn() {}, debug() {} };
assert.strictEqual(await migratePlaintextTotpSecrets({ db, secretCrypto, logger }), 0);
assert.strictEqual(row.secret, replacement, "migration must preserve the winning credential state");
assert.strictEqual(row.session_epoch, 42);
assert.deepStrictEqual(logs, [], "a CAS loser must not report a sealed row");
}
});
test("legacy seed migration leaves plaintext untouched when sealing or database work fails", async () => {
const row = { id: 7, secret: SEED };
const notes = [];
let writes = 0;
const db = {
pool: { query: async () => [[row]] },
query: async () => { writes += 1; throw new Error("database-unavailable"); },
};
const logger = { log() {}, warn: (message) => notes.push(message), debug: (message) => notes.push(message) };
assert.strictEqual(await migratePlaintextTotpSecrets({ db, logger, secretCrypto: {
isTotpSecretEnvelope: () => false, encryptTotpSecret: () => null,
} }), 0);
assert.strictEqual(writes, 0);
assert.strictEqual(await migratePlaintextTotpSecrets({ db, logger, secretCrypto: freshModule({ SESSION_SECRET }) }), 0);
assert.strictEqual(row.secret, SEED);
assert.strictEqual(notes.length, 2);
});
// The module caches its derived key at module level (_keyCache) for the
// process lifetime, so every derivation scenario loads a FRESH instance under
// that scenario's env — the same isolation mechanism the worker-isolation
// tests use (tests/db-proxy-cluster-token-store.test.js); no reset API is
// added to the shipped module. node --test runs this file in its own process,
// so env mutation here cannot leak into other test files, and every scenario
// deletes-then-sets both variables so it is self-contained.
function freshModule(env) {
delete process.env.SESSION_SECRET;
delete process.env.TOTP_SEALING_KEY;
for (const [name, value] of Object.entries(env || {})) {
if (value !== undefined) process.env[name] = value;
}
delete require.cache[MODULE_PATH];
return require(MODULE_PATH);
}
// Independent envelope machinery — deliberately NOT the module under test, so
// the cross-decryption pins below compare against a from-scratch AES-256-GCM
// implementation of the documented envelope format.
function sealWithKey(key, plaintext) {
const iv = crypto.randomBytes(12);
const cipher = crypto.createCipheriv("aes-256-gcm", key, iv, { authTagLength: 16 });
const ct = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
return `${ENC_PREFIX}${iv.toString("base64")}:${cipher.getAuthTag().toString("base64")}:${ct.toString("base64")}`;
}
function openWithKey(key, envelope) {
const [ivB64, tagB64, ctB64] = envelope.slice(ENC_PREFIX.length).split(":");
const decipher = crypto.createDecipheriv("aes-256-gcm", key, Buffer.from(ivB64, "base64"), { authTagLength: 16 });
decipher.setAuthTag(Buffer.from(tagB64, "base64"));
return Buffer.concat([decipher.update(Buffer.from(ctB64, "base64")), decipher.final()]).toString("utf8");
}
function derivedSessionKey(salt) {
// The pre-override algorithm, computed independently in the test.
return crypto.scryptSync(SESSION_SECRET, salt || "adpanel-totp-secret-v1", 32);
}
test("unset override: the sealing key stays byte-identical to the pre-override derivation — scrypt(SESSION_SECRET, salt, 32)", () => {
const mod = freshModule({ SESSION_SECRET });
const expectedKey = derivedSessionKey();
assert.strictEqual(mod.SALT, "adpanel-totp-secret-v1", "the TOTP-specific salt is pinned");
// Direction 1: a manual envelope under the independently computed key must
// open through the module — GCM verification only passes under the exact
// key bytes, so this proves the module derived exactly that key.
assert.strictEqual(
mod.decryptTotpSecret(sealWithKey(expectedKey, SEED)),
SEED,
"module opens an envelope sealed with the independent pre-override key"
);
// Direction 2: the module's own seal must open under the independently
// computed key — proving no other input (and no param drift) feeds the KDF.
const sealed = mod.encryptTotpSecret(SEED);
assert.ok(mod.isTotpSecretEnvelope(sealed));
assert.strictEqual(
openWithKey(expectedKey, sealed),
SEED,
"the independent pre-override key opens the module's seal"
);
});
test("set override: seal+unseal roundtrip succeeds under the same override, with key material distinct from the SESSION_SECRET derivation", () => {
const mod = freshModule({ SESSION_SECRET, TOTP_SEALING_KEY: OVERRIDE });
const sealed = mod.encryptTotpSecret(SEED);
assert.ok(mod.isTotpSecretEnvelope(sealed), "the seal is a v1 envelope");
assert.strictEqual(mod.decryptTotpSecret(sealed), SEED, "roundtrip under the same override");
// Distinct material: the override-sealed envelope must NOT open under the
// scrypt(SESSION_SECRET) key — the decipher fails authentication.
assert.throws(
() => openWithKey(derivedSessionKey(), sealed),
"the override key material differs from the SESSION_SECRET derivation"
);
// And the KDF input is the OVERRIDE, not the session secret: an
// independently computed scrypt(OVERRIDE, salt, 32) key opens the seal.
const overrideKey = crypto.scryptSync(OVERRIDE, mod.SALT, 32);
assert.strictEqual(
mod.decryptTotpSecret(sealWithKey(overrideKey, SEED)),
SEED,
"the module derives from the override input"
);
});
test("fail-closed: a seal minted under one derivation can NEVER be opened under the other (no fallback)", () => {
// Sealed under the derived key (override unset)…
const sealer = freshModule({ SESSION_SECRET });
const sealedDerived = sealer.encryptTotpSecret(SEED);
// …an override-keyed module must fail CLOSED — null, never the seed.
const opener = freshModule({ SESSION_SECRET, TOTP_SEALING_KEY: OVERRIDE });
assert.strictEqual(
opener.decryptTotpSecret(sealedDerived),
null,
"derived-key seal under the override decrypts to null (fail-closed, no fallback)"
);
// And the reverse direction: sealed under the override…
const sealedOverride = opener.encryptTotpSecret(SEED);
// …a derived-key module must also fail closed.
const derivedOpener = freshModule({ SESSION_SECRET });
assert.strictEqual(
derivedOpener.decryptTotpSecret(sealedOverride),
null,
"override seal under the derived key decrypts to null (fail-closed, no fallback)"
);
});
test("empty-string override is treated exactly like unset, matching the boot check's `override !== \"\"` guard", () => {
const unsetMod = freshModule({ SESSION_SECRET });
const sealed = unsetMod.encryptTotpSecret(SEED);
const emptyMod = freshModule({ SESSION_SECRET, TOTP_SEALING_KEY: "" });
assert.strictEqual(
emptyMod.decryptTotpSecret(sealed),
SEED,
"an empty override keeps the SESSION_SECRET-derived key"
);
// Same proof in the encryption direction: the empty-override module's seal
// opens under the independently computed pre-override key.
assert.strictEqual(openWithKey(derivedSessionKey(), emptyMod.encryptTotpSecret(SEED)), SEED);
});
test("the fail-closed decrypt posture is untouched: a tampered envelope decrypts to null under either derivation", () => {
const derived = freshModule({ SESSION_SECRET });
const override = freshModule({ SESSION_SECRET, TOTP_SEALING_KEY: OVERRIDE });
const tamper = (envelope) => {
const [ivB64, tagB64, ctB64] = envelope.slice(ENC_PREFIX.length).split(":");
const tag = Buffer.from(tagB64, "base64");
tag[0] ^= 0xff;
return `${ENC_PREFIX}${ivB64}:${tag.toString("base64")}:${ctB64}`;
};
assert.strictEqual(derived.decryptTotpSecret(tamper(override.encryptTotpSecret(SEED))), null);
assert.strictEqual(override.decryptTotpSecret(tamper(derived.encryptTotpSecret(SEED))), null);
});
// ─── Source pins: boot-check wiring and constraint comments ───
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}`);
}
test("source-pin: TOTP_SEALING_KEY is checked through the shared boot-check helper beside its three siblings", () => {
const indexSource = fs.readFileSync(INDEX_JS, "utf8");
const names = ["REMEMBER_LOGIN_SECRET", "ACTION_TOKEN_SECRET", "SSH_TERM_TOKEN_SECRET", "TOTP_SEALING_KEY"];
const positions = names.map((name) => indexSource.indexOf(`requireStrongSecretOverride("${name}")`));
positions.forEach((position, i) => {
assert.ok(position > -1, `${names[i]} must be checked through the shared helper`);
});
assert.ok(positions[3] > positions[2], "TOTP_SEALING_KEY sits beside the sibling calls");
const helperAt = indexSource.indexOf("function requireStrongSecretOverride(name)");
assert.ok(helperAt > -1, "the shared helper exists");
assert.strictEqual(
indexSource.indexOf("function requireStrongSecretOverride(name)", helperAt + 1),
-1,
"the helper stays defined exactly once — the fourth override is a call, not a copy"
);
assert.ok(
indexSource.includes("adpanel:totp-sealing-key-override"),
"the constraint comment exists at the boot-check site"
);
});
test("source-pin: the real helper body enforces the 32-char floor on TOTP_SEALING_KEY (short → exit(1); unset/empty → legal)", () => {
const indexSource = fs.readFileSync(INDEX_JS, "utf8");
const helper = indexSource.slice(
indexSource.indexOf("function requireStrongSecretOverride(name)"),
endIndexOfFunction(indexSource, "function requireStrongSecretOverride(name)")
);
const run = (env) => {
const context = vm.createContext({
process: { env, exit: (code) => { throw new Error(`__exit__:${code}`); } },
console: { error: () => {} },
});
return vm.runInContext(`${helper}\nrequireStrongSecretOverride`, context);
};
assert.doesNotThrow(() => run({ TOTP_SEALING_KEY: "a".repeat(32) })("TOTP_SEALING_KEY"), "32 chars must be accepted");
assert.throws(() => run({ TOTP_SEALING_KEY: "a".repeat(31) })("TOTP_SEALING_KEY"), (err) => err.message === "__exit__:1", "31 chars must exit(1)");
assert.doesNotThrow(() => run({})("TOTP_SEALING_KEY"), "unset must stay legal (keeps the derived key)");
assert.doesNotThrow(() => run({ TOTP_SEALING_KEY: "" })("TOTP_SEALING_KEY"), "empty must stay legal (keeps the derived key)");
});
test("source-pin: the boot advisory fires only when the override is ACTIVE, after the boot check", () => {
const indexSource = fs.readFileSync(INDEX_JS, "utf8");
const advisoryAt = indexSource.indexOf("[config] TOTP_SEALING_KEY override active");
assert.ok(advisoryAt > -1, "the boot advisory is present");
assert.ok(
indexSource.includes("can no longer be decrypted and require re-enrollment; set the override once and keep it stable"),
"the advisory names the fail-closed re-enrollment consequence"
);
const gateAt = indexSource.lastIndexOf("if (process.env.TOTP_SEALING_KEY)", advisoryAt);
assert.ok(gateAt > -1, "the advisory is gated on the override being set");
const bootCallAt = indexSource.indexOf('requireStrongSecretOverride("TOTP_SEALING_KEY")');
assert.ok(gateAt > bootCallAt, "the advisory runs after the strength check (a short override exits before any advisory)");
});
test("source-pin: the derivation site changes only the KDF input and carries the constraint comment", () => {
const moduleSource = fs.readFileSync(MODULE_JS, "utf8");
assert.strictEqual(
moduleSource.split("process.env.TOTP_SEALING_KEY || process.env.SESSION_SECRET").length - 1,
1,
"exactly ONE derivation site — the ||-fallback replaces the bare SESSION_SECRET read"
);
assert.ok(
moduleSource.includes("process.env.TOTP_SEALING_KEY || process.env.SESSION_SECRET || \"\""),
"the override || SESSION_SECRET fallback feeds the same scrypt input"
);
assert.ok(
moduleSource.includes("adpanel:totp-sealing-key-override"),
"the constraint comment exists at the derivation site"
);
assert.ok(
moduleSource.includes("crypto.scryptSync(secret, SALT, 32)"),
"the KDF call keeps its salt and 32-byte length"
);
});