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

+838
View File
@@ -0,0 +1,838 @@
"use strict";
// adpanel:stepup-proof-strength — a grace grant must never satisfy a STRONGER
// verification requirement than the proof that minted it. Before this fix a
// grant recorded no proof strength, so a grant minted by the legacy either/or
// verification (TOTP alone — e.g. the "Security settings update" gate) happily
// unlocked the nine credentialFlow "password-then-totp" Accounts-tab gates
// with ZERO password verification.
//
// Locked here:
// - verifyDestructiveActionStepUp records the strength ACHIEVED by the
// branch actually taken ("password+totp" / "password" / "totp") on its
// success returns; every minted grant persists it (DB row = source of
// truth, memory mirror + session state ride along additively).
// - The grace block of requireDestructiveActionStepUp enforces the strength
// ONLY for credentialFlow "password-then-totp" gates: needed =
// "password+totp" when the acting admin has 2FA, else "password";
// satisfied by "password+totp" always, "password" only at the password
// level; "totp" and NULL/unknown NEVER satisfy (conservative for older
// rows). A too-weak grant is NOT consumed or cleared — it stays valid for
// weaker either/or gates — and the request falls through to a fresh
// verification exactly like the spent/retargeted path.
// - Either/or gates are unchanged: any live grant still satisfies them
// (peer-admin allowGrace:false and requireDatabaseInstallStepUp's legacy
// shape are pinned elsewhere and ride this unchanged).
// - Expiry, reuse cap, target scoping and revocation behave exactly as
// before, with the strength check layered ahead of consumption.
// - A DB without the proof_strength column degrades the INSERT and the
// SELECT; unknown strength is conservative (one extra fresh verification,
// bounded by the 5-minute grant TTL).
//
// Harness: the house vm-extraction technique — the REAL constants, helpers
// and step-up functions are extracted from index.js verbatim and run against
// a stateful fake db that emulates the real conditional-consumption SQL (and
// the ER_BAD_FIELD_ERROR column degradation), the REAL safeCompare /
// ACTION_TOKEN_SECRET / strength module, and fake credential verifiers that
// record every proof they are asked to check.
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 crypto = require("node:crypto");
const ROOT = path.join(__dirname, "..");
const INDEX_JS = path.join(ROOT, "index.js");
const indexSource = fs.readFileSync(INDEX_JS, "utf8");
const {
STEP_UP_PROOF_STRENGTHS,
achievedStepUpProofStrength,
requiredStepUpProofStrength,
proofStrengthSatisfies,
normalizeStepUpProofStrength,
} = require("../utils/step-up-proof-strength.js");
function sliceBetween(source, startMarker, endMarker) {
const start = source.indexOf(startMarker);
assert.ok(start >= 0, `start marker not found: ${startMarker}`);
const end = source.indexOf(endMarker, start + startMarker.length);
assert.ok(end > start, `end marker not found after start: ${endMarker}`);
return source.slice(start, end);
}
function countOccurrences(haystack, needle) {
return haystack.split(needle).length - 1;
}
// ---------------------------------------------------------------------------
// The REAL machinery, extracted from index.js
// ---------------------------------------------------------------------------
const SAFE_COMPARE_SLICE = sliceBetween(
indexSource,
"function safeCompare(a, b) {",
"const ACTION_TOKEN_SECRET ="
);
const ACTION_SECRET_SLICE = sliceBetween(
indexSource,
"const ACTION_TOKEN_SECRET =",
"const SSH_TERM_TOKEN_SECRET ="
);
const CONST_SLICE = sliceBetween(
indexSource,
"const SESSION_REVOKE_2FA_GRACE_MAX_MS = 5 * 60 * 1000;",
"const activeBrowserSessionCache = {"
);
const GRACE_SLICE = sliceBetween(
indexSource,
"function hashDestructiveActionGraceValue(label, value) {",
"function getOpaqueDisplayHandle("
);
const NOW0 = 1700000000000;
// Stateful fake db modeling destructive_action_grants: column presence is
// configurable (degraded deployments), INSERT/SELECT throw ER_BAD_FIELD_ERROR
// for missing columns exactly like MySQL, and the consume UPDATE reproduces
// the real conditional semantics (revoked/expired/cap/scope predicates,
// use_count increment, COALESCE scope binding).
function makeGrantDb({ columns } = {}) {
const colPresence = {
grant_id: true,
user_id: true,
email: true,
session_hash: true,
secret_hash: true,
ip_hash: true,
ua_hash: true,
verified_at: true,
expires_at: true,
revoked_at: true,
subject: true,
created_at: true,
use_count: true,
scope_hash: true,
proof_strength: true,
...(columns || {}),
};
const rows = new Map(); // grant_id -> snake_case row
const queries = [];
const badField = (col) =>
Object.assign(new Error(`Unknown column '${col}' in 'field list'`), { code: "ER_BAD_FIELD_ERROR" });
return {
rows,
queries,
colPresence,
async query(sql, params = []) {
queries.push({ sql, params });
const insertMatch = /INSERT INTO destructive_action_grants\s*\(([^)]*)\)/.exec(sql);
if (insertMatch) {
const cols = insertMatch[1].split(",").map((c) => c.trim());
const missing = cols.find((c) => !colPresence[c]);
if (missing) throw badField(missing);
assert.equal(cols.length, params.length, "harness: insert column/param count mismatch");
const row = {};
cols.forEach((c, i) => { row[c] = params[i]; });
rows.set(row.grant_id, row);
return { affectedRows: 1 };
}
const selectMatch = /SELECT ([\s\S]+?)\s+FROM destructive_action_grants\s+WHERE grant_id\s*=\s*\?\s*LIMIT\s+1/.exec(sql);
if (selectMatch) {
const cols = selectMatch[1].split(",").map((c) => c.trim());
const missing = cols.find((c) => !colPresence[c]);
if (missing) throw badField(missing);
const row = rows.get(params[0]);
if (!row) return [];
const out = {};
for (const c of cols) out[c] = row[c] === undefined ? null : row[c];
return [out];
}
if (sql.includes("UPDATE destructive_action_grants")) {
const scoped = sql.includes("COALESCE(scope_hash, ?)");
const grantId = scoped ? params[1] : params[0];
const now = scoped ? params[2] : params[1];
const cap = scoped ? params[3] : params[2];
const row = rows.get(grantId);
if (!row) return { affectedRows: 0 };
if (row.revoked_at !== null && row.revoked_at !== undefined) return { affectedRows: 0 };
if (Number(row.expires_at || 0) <= now) return { affectedRows: 0 };
if (Number(row.use_count || 0) >= cap) return { affectedRows: 0 };
if (scoped) {
const scopeHash = params[0];
const whereHash = params[4];
const bound = row.scope_hash == null ? null : row.scope_hash;
if (bound !== null && bound !== whereHash) return { affectedRows: 0 };
row.scope_hash = bound === null ? scopeHash : bound;
} else if (row.scope_hash !== null && row.scope_hash !== undefined) {
return { affectedRows: 0 };
}
row.use_count = Number(row.use_count || 0) + 1;
return { affectedRows: 1 };
}
if (sql.includes("DELETE FROM destructive_action_grants")) {
const now = params[0];
let removed = 0;
for (const [id, r] of Array.from(rows)) {
if (Number(r.expires_at || 0) <= now || (r.revoked_at !== null && r.revoked_at !== undefined)) {
rows.delete(id);
removed += 1;
}
}
return { affectedRows: removed };
}
throw new Error(`harness: unexpected db.query: ${sql}`);
},
};
}
// Loads the REAL grace machinery into a vm sandbox. Returns the exported
// functions plus every spy the assertions need.
function loadGraceMachinery({ columns, passwordOk = true, startNow = NOW0, sharedDb } = {}) {
const db = sharedDb || makeGrantDb({ columns });
const clock = { now: startNow };
const passwordCalls = [];
const totpCalls = [];
const sandbox = {
process: { env: { SESSION_SECRET: "harness-session-secret" } },
crypto,
Buffer,
Math,
Number,
String,
Object,
Promise,
Date: { now: () => clock.now },
parseInt,
console: { log: () => {}, warn: () => {}, error: () => {}, debug: () => {} },
db,
withTimeout: (p) => Promise.resolve(p),
hasTwoFactorEnabled: (user) => !!(user && String(user?.secret || "").trim()),
normalizeTotpCode: (raw) => {
const c = String(raw || "").replace(/\s+/g, "");
return /^\d{6}$/.test(c) ? c : "";
},
verifyPasswordForUser: async (_user, raw) => {
passwordCalls.push(raw);
return passwordOk;
},
verifyTotpForUser: async (_user, raw) => {
totpCalls.push(raw);
const c = String(raw || "").replace(/\s+/g, "");
if (!/^\d{6}$/.test(c)) return { ok: false, code: "invalid-format" };
return { ok: true, skipped: false };
},
getRequestIp: () => "127.0.0.1",
getScopeKeyLogForm: (k) => String(k || ""),
// The REAL strength module (the one index.js requires).
...require("../utils/step-up-proof-strength.js"),
...require("../utils/destructive-action-credentials.js"),
readVerifiedActionGrant: (deps) => require("../services/destructive-action-grants").readVerifiedActionGrant({ ...deps, now: () => clock.now }),
};
const __harness = {};
sandbox.__harness = __harness;
const script = [SAFE_COMPARE_SLICE, ACTION_SECRET_SLICE, CONST_SLICE, GRACE_SLICE].join("\n") + `
;Object.assign(__harness, {
requireDestructiveActionStepUp,
requireDatabaseInstallStepUp,
verifyDestructiveActionStepUp,
getVerifiedSessionRevokeGraceState,
hasSessionRevokeGrace,
getSessionRevokeGraceState,
setSessionRevokeGrace,
persistDestructiveActionGrace,
consumeDestructiveActionGraceUse,
clearSessionRevokeGrace,
getDestructiveActionGraceScopeHash,
destructiveActionGraceMemory,
graceMs: SESSION_REVOKE_2FA_GRACE_MS,
maxUses: SESSION_REVOKE_2FA_GRACE_MAX_USES,
});
`;
vm.runInContext(script, vm.createContext(sandbox), { filename: "index.js[grace-machinery]" });
return { ...__harness, db, clock, passwordCalls, totpCalls };
}
function makeUser({ twoFactorEnabled = true, id = 42, email = "admin@example.test" } = {}) {
return {
id,
email,
password: "$2a$12$storedhash",
secret: twoFactorEnabled ? "JBSWY3DPEHPK3PXP" : null,
};
}
function makeReq() {
return {
body: {},
sessionID: "harness-sid",
session: { user: "admin@example.test", save(cb) { cb(null); } },
get: (k) => (String(k).toLowerCase() === "user-agent" ? "test-agent" : undefined),
};
}
function makeRes() {
const res = { statusCode: 0, body: null };
res.status = (code) => { res.statusCode = code; return res; };
res.json = (body) => { res.body = body; return res; };
return res;
}
// Runs one requireDestructiveActionStepUp call with the given payload/options
// and clears the payload afterwards (a later no-payload attempt must not
// inherit credentials).
async function gate(h, { req, res, user, subject = "Harness gate", flow = null, scopeKey = null, body = {} } = {}) {
const options = {};
if (flow) options.credentialFlow = flow;
if (scopeKey !== null) options.scopeKey = scopeKey;
req.body = body;
const out = await h.requireDestructiveActionStepUp(req, res, user, subject, options);
req.body = {};
return out;
}
// Fresh verification that mints a grant: either/or TOTP-only by default, or
// the password-first flow when `flow` is given.
async function mintGrant(h, { req, res, user, flow = null, scopeKey = null, twoFactorEnabled = true } = {}) {
const body = flow === "password-then-totp"
? { currentPassword: "correct-password", ...(twoFactorEnabled ? { twoFactorCode: "111111" } : {}) }
: { twoFactorCode: "111111" };
const options = {};
if (flow) options.credentialFlow = flow;
if (scopeKey !== null) options.scopeKey = scopeKey;
req.body = body;
const out = await h.requireDestructiveActionStepUp(req, res, user, "Harness mint", options);
req.body = {};
assert.equal(out.ok, true, "mint precondition: fresh verification succeeded");
assert.equal(out.usedFreshVerification, true, "mint precondition: fresh verification minted the grant");
return out;
}
// ---------------------------------------------------------------------------
// Unit tests — the strength vocabulary and the conservative satisfaction rule
// ---------------------------------------------------------------------------
test("achievedStepUpProofStrength maps the verification branch actually taken", () => {
assert.equal(achievedStepUpProofStrength("password-then-totp", "2fa"), "password+totp");
assert.equal(achievedStepUpProofStrength("password-then-totp", "password"), "password");
// Legacy either/or: 2FA-enabled admin proves the TOTP ALONE (no password).
assert.equal(achievedStepUpProofStrength(undefined, "2fa"), "totp");
assert.equal(achievedStepUpProofStrength(undefined, "password"), "password");
// Unrecordable proofs collapse to null, never to a strong value.
assert.equal(achievedStepUpProofStrength("password-then-totp", "weird"), null);
assert.equal(achievedStepUpProofStrength(undefined, undefined), null);
});
test("requiredStepUpProofStrength: only password-then-totp gates impose a requirement", () => {
assert.equal(requiredStepUpProofStrength("password-then-totp", true), "password+totp");
assert.equal(requiredStepUpProofStrength("password-then-totp", false), "password");
for (const flow of [undefined, null, "", "either-or", "password-first"]) {
assert.equal(requiredStepUpProofStrength(flow, true), null, `flow ${String(flow)} imposes no requirement`);
}
});
test("proofStrengthSatisfies: password+totp always, password only at password level, totp/NULL never", () => {
assert.equal(proofStrengthSatisfies("password+totp", "password+totp"), true);
assert.equal(proofStrengthSatisfies("password+totp", "password"), true);
assert.equal(proofStrengthSatisfies("password", "password"), true);
assert.equal(proofStrengthSatisfies("password", "password+totp"), false);
assert.equal(proofStrengthSatisfies("totp", "password+totp"), false);
assert.equal(proofStrengthSatisfies("totp", "password"), false);
assert.equal(proofStrengthSatisfies(null, "password+totp"), false);
assert.equal(proofStrengthSatisfies(null, "password"), false);
assert.equal(proofStrengthSatisfies(undefined, "password"), false);
assert.equal(proofStrengthSatisfies("", "password"), false);
assert.equal(proofStrengthSatisfies("password+totp", null), false);
assert.equal(proofStrengthSatisfies("garbage", "password"), false);
});
test("normalizeStepUpProofStrength collapses unknown/legacy values to null", () => {
assert.equal(normalizeStepUpProofStrength("password+totp"), "password+totp");
assert.equal(normalizeStepUpProofStrength("password"), "password");
assert.equal(normalizeStepUpProofStrength("totp"), "totp");
assert.equal(normalizeStepUpProofStrength(null), null);
assert.equal(normalizeStepUpProofStrength(undefined), null);
assert.equal(normalizeStepUpProofStrength(""), null);
assert.equal(normalizeStepUpProofStrength("legacy-unknown"), null);
});
// ---------------------------------------------------------------------------
// Behavior — the bypass and its fix
// ---------------------------------------------------------------------------
test("step-up rejects non-string credentials before password or TOTP verification", async () => {
for (const invalid of [111111, ["111111"], { code: "111111" }, true]) {
for (const flow of [undefined, "password-then-totp"]) {
const h = loadGraceMachinery();
const req = makeReq();
req.body = { currentPassword: invalid, twoFactorCode: invalid };
const out = await h.verifyDestructiveActionStepUp(req, makeUser(), "Type regression", { credentialFlow: flow });
assert.equal(out.ok, false);
assert.equal(h.passwordCalls.length, 0);
assert.equal(h.totpCalls.length, 0);
}
}
});
test("install verification cannot accept numeric TOTP outside its credential budget", async () => {
const h = loadGraceMachinery();
const req = makeReq();
for (let attempt = 0; attempt < 12; attempt += 1) {
req.body = { twoFactorCode: 111111 };
const out = await h.requireDatabaseInstallStepUp(req, makeRes(), makeUser(), "Install regression");
assert.equal(out.ok, false);
}
assert.equal(h.totpCalls.length, 0);
assert.equal(h.passwordCalls.length, 0);
});
test("credential admission uses the same strict parser as step-up verification", () => {
const { parseDestructiveActionCredentials, hasDestructiveActionCredentialPayload } = require("../utils/destructive-action-credentials");
assert.equal(parseDestructiveActionCredentials({ twoFactorCode: "012345" }).twoFactorCode, "012345");
assert.equal(hasDestructiveActionCredentialPayload({ body: { twoFactorCode: "012345" } }), true);
assert.equal(hasDestructiveActionCredentialPayload({ body: { currentPassword: "correct" } }), true);
for (const invalid of [123456, ["123456"], {}, true, null]) {
assert.equal(hasDestructiveActionCredentialPayload({ body: { twoFactorCode: invalid } }), false);
assert.equal(parseDestructiveActionCredentials({ twoFactorCode: invalid }).invalidType, true);
}
});
test("REPRO: a TOTP-only grant cannot satisfy a password-then-totp gate — no-payload attempt is challenged and the grant survives untouched", async () => {
const h = loadGraceMachinery();
const user = makeUser({ twoFactorEnabled: true });
const req = makeReq();
const res = makeRes();
// 1. A TOTP-only grant minted by the legacy either/or path (the
// "Security settings update" shape: one TOTP code, no password).
await mintGrant(h, { req, res, user });
const oldGrantId = req.session.sessionRevoke2fa.grantId;
assert.ok(h.db.rows.get(oldGrantId), "the grant is persisted");
// 2. The same session hits a password-then-totp gate with NO payload.
const challenge = await gate(h, {
req, res, user,
subject: 'Password reset for "victim@example.test"',
flow: "password-then-totp",
scopeKey: "user:victim@example.test",
});
assert.equal(challenge.ok, false, "the TOTP-only grant must NOT satisfy the password-first gate");
assert.equal(challenge.handled, true);
assert.equal(res.statusCode, 403);
assert.equal(res.body.code, "password-required", "the challenge must demand the password");
assert.equal(h.passwordCalls.length, 0, "no password was verified — the gate is demanding one");
// The too-weak grant is deliberately NOT consumed or cleared: it stays
// valid for weaker either/or gates until it expires.
assert.ok(req.session.sessionRevoke2fa, "the grant stays in the session");
assert.ok(h.db.rows.get(oldGrantId), "the grant row stays alive");
assert.equal(Number(h.db.rows.get(oldGrantId).use_count || 0), 0, "the grant was never consumed");
});
test("REPRO: with credentials present the weak grant falls through — the password IS verified and a stronger grant is minted", async () => {
const h = loadGraceMachinery();
const user = makeUser({ twoFactorEnabled: true });
const req = makeReq();
const res = makeRes();
await mintGrant(h, { req, res, user });
const oldGrantId = req.session.sessionRevoke2fa.grantId;
const passwordsBefore = h.passwordCalls.length;
const out = await gate(h, {
req, res, user,
subject: 'Password reset for "victim@example.test"',
flow: "password-then-totp",
scopeKey: "user:victim@example.test",
body: { currentPassword: "correct-password", twoFactorCode: "222222" },
});
assert.equal(out.ok, true);
assert.equal(
out.usedFreshVerification,
true,
"the TOTP-only grant must NOT satisfy a password-then-totp gate (pre-fix this returned false: the bypass)"
);
assert.ok(
h.passwordCalls.length > passwordsBefore,
"the password must actually be verified (pre-fix zero password checks happened)"
);
// A NEW grant with the stronger recorded strength replaced the old one.
const newGrantId = req.session.sessionRevoke2fa.grantId;
assert.notEqual(newGrantId, oldGrantId, "a fresh grant was minted");
assert.equal(h.db.rows.get(newGrantId).proof_strength, "password+totp", "the DB row records the achieved strength");
assert.equal(h.destructiveActionGraceMemory.get(newGrantId).proofStrength, "password+totp", "the memory mirror records it");
assert.equal(req.session.sessionRevoke2fa.proofStrength, "password+totp", "the session state rides along");
// The old grant was never consumed — it simply does not qualify here.
assert.equal(Number(h.db.rows.get(oldGrantId).use_count || 0), 0);
});
test("a NULL/unknown-strength grant (older row) is rejected for password-then-totp — conservative", async () => {
const h = loadGraceMachinery();
const user = makeUser({ twoFactorEnabled: true });
const req = makeReq();
const res = makeRes();
await mintGrant(h, { req, res, user, flow: "password-then-totp", scopeKey: "user:victim@example.test" });
const grantId = req.session.sessionRevoke2fa.grantId;
// Emulate a pre-migration row (deploy-time in-flight grants have NULL).
h.db.rows.get(grantId).proof_strength = null;
const out = await gate(h, {
req, res, user,
flow: "password-then-totp",
scopeKey: "user:victim@example.test",
body: { currentPassword: "correct-password", twoFactorCode: "333333" },
});
assert.equal(out.ok, true);
assert.equal(out.usedFreshVerification, true, "NULL strength never satisfies — fresh verification ran");
assert.ok(h.passwordCalls.length >= 1, "the password was verified again");
assert.notEqual(req.session.sessionRevoke2fa.grantId, grantId, "a fresh grant replaced the legacy row");
});
// ---------------------------------------------------------------------------
// Behavior — correctly-verified grants keep working; every other grant
// property is unchanged
// ---------------------------------------------------------------------------
test("a password+totp grant DOES satisfy same-target password-then-totp reuse (COALESCE scope binding + use cap preserved)", async () => {
const h = loadGraceMachinery();
const user = makeUser({ twoFactorEnabled: true });
const req = makeReq();
const res = makeRes();
await mintGrant(h, { req, res, user, flow: "password-then-totp", scopeKey: "user:victim@example.test" });
const grantId = req.session.sessionRevoke2fa.grantId;
const row = h.db.rows.get(grantId);
assert.equal(row.proof_strength, "password+totp");
assert.equal(row.scope_hash, h.getDestructiveActionGraceScopeHash("user:victim@example.test"), "the grant is pre-bound to its target");
assert.ok(h.passwordCalls.length >= 1, "the mint verified the password");
const passwordsAfterMint = h.passwordCalls.length;
const reuse1 = await gate(h, { req, res, user, flow: "password-then-totp", scopeKey: "user:victim@example.test" });
assert.equal(reuse1.ok, true);
assert.equal(reuse1.usedFreshVerification, false, "the strong grant rode the grace window");
assert.equal(reuse1.graceUsesRemaining, h.maxUses - 1);
assert.equal(h.passwordCalls.length, passwordsAfterMint, "no fresh credential proof was demanded");
assert.equal(req.session.sessionRevoke2fa.grantId, grantId, "same grant reused");
assert.equal(Number(h.db.rows.get(grantId).use_count), 1, "the reuse was counted");
const reuse2 = await gate(h, { req, res, user, flow: "password-then-totp", scopeKey: "user:victim@example.test" });
assert.equal(reuse2.ok, true);
assert.equal(Number(h.db.rows.get(grantId).use_count), 2, "cap accounting continues");
});
test("a different worker with no local cache accepts a valid shared grant", async () => {
const h = loadGraceMachinery();
const req = makeReq();
const res = makeRes();
const user = makeUser();
await mintGrant(h, { req, res, user, flow: "password-then-totp", scopeKey: "user-id:42" });
const id = req.session.sessionRevoke2fa.grantId;
h.destructiveActionGraceMemory.clear();
h.db.rows.get(id).use_count = 2;
const state = await h.getVerifiedSessionRevokeGraceState(req, user);
assert.ok(state);
assert.equal(state.useCount, 2);
const out = await gate(h, { req, res, user, flow: "password-then-totp", scopeKey: "user-id:42" });
assert.equal(out.ok, true);
assert.equal(out.usedFreshVerification, false);
assert.equal(h.db.rows.get(id).use_count, 3);
});
test("separate workers share immutable target scopes and concurrent reuse caps", async () => {
const first = loadGraceMachinery();
const second = loadGraceMachinery({ sharedDb: first.db });
const user = makeUser();
const req = makeReq();
await mintGrant(first, { req, res: makeRes(), user, flow: "password-then-totp", scopeKey: "user-id:42" });
const otherReq = makeReq();
otherReq.session.sessionRevoke2fa = JSON.parse(JSON.stringify(req.session.sessionRevoke2fa));
assert.equal(second.destructiveActionGraceMemory.size, 0);
const states = await Promise.all([first.getVerifiedSessionRevokeGraceState(req, user), second.getVerifiedSessionRevokeGraceState(otherReq, user)]);
const outcomes = await Promise.all([
first.consumeDestructiveActionGraceUse(req, user, states[0], "Concurrent one", "user-id:42"),
second.consumeDestructiveActionGraceUse(otherReq, user, states[1], "Concurrent two", "user-id:42")
]);
assert(outcomes.every(Boolean));
assert(outcomes.every((outcome) => outcome.useCount === 2), "post-consumption metadata follows the shared committed count");
const replacement = await gate(second, { req: otherReq, res: makeRes(), user, flow: "password-then-totp", scopeKey: "user-id:43" });
assert.equal(replacement.ok, false, "the same-email replacement cannot inherit the old row's grant");
const id = req.session.sessionRevoke2fa.grantId;
assert.equal(first.db.rows.get(id).use_count, 2);
first.db.rows.get(id).revoked_at = first.clock.now;
assert.equal(await first.getVerifiedSessionRevokeGraceState(req, user), null, "a local positive cache never overrides shared revocation");
});
test("a 2FA-less admin's password grant satisfies the password-level password-then-totp requirement", async () => {
const h = loadGraceMachinery();
const user = makeUser({ twoFactorEnabled: false });
const req = makeReq();
const res = makeRes();
await mintGrant(h, { req, res, user, flow: "password-then-totp", scopeKey: "user:victim@example.test" });
const grantId = req.session.sessionRevoke2fa.grantId;
assert.equal(h.db.rows.get(grantId).proof_strength, "password", "password-only proof for a 2FA-less admin");
const reuse = await gate(h, { req, res, user, flow: "password-then-totp", scopeKey: "user:victim@example.test" });
assert.equal(reuse.ok, true);
assert.equal(reuse.usedFreshVerification, false, "needed 'password' is satisfied by achieved 'password'");
});
test("expiry, reuse cap, target scoping and revocation are unchanged", async () => {
// Expiry: a live strong grant past its expiry falls through to fresh
// verification (candidate rejects expiresAt <= now, fail-closed).
{
const h = loadGraceMachinery();
const user = makeUser({ twoFactorEnabled: true });
const req = makeReq();
const res = makeRes();
await mintGrant(h, { req, res, user, flow: "password-then-totp", scopeKey: "user:v@example.test" });
const grantId = req.session.sessionRevoke2fa.grantId;
h.clock.now = Number(h.db.rows.get(grantId).expires_at) + 1;
const out = await gate(h, {
req, res, user, flow: "password-then-totp", scopeKey: "user:v@example.test",
body: { currentPassword: "correct-password", twoFactorCode: "444444" },
});
assert.equal(out.ok, true);
assert.equal(out.usedFreshVerification, true, "expired grants never satisfy");
assert.ok(h.passwordCalls.length >= 1, "fresh verification ran");
}
// Reuse cap: after maxUses reuses the grant is spent and the next
// no-payload attempt is challenged (cap fails closed, unchanged).
{
const h = loadGraceMachinery();
const user = makeUser({ twoFactorEnabled: true });
const req = makeReq();
const res = makeRes();
await mintGrant(h, { req, res, user, flow: "password-then-totp", scopeKey: "user:v@example.test" });
const grantId = req.session.sessionRevoke2fa.grantId;
assert.equal(h.maxUses, 5, "the hard cap is unchanged");
for (let i = 1; i <= h.maxUses; i += 1) {
const reuse = await gate(h, { req, res, user, flow: "password-then-totp", scopeKey: "user:v@example.test" });
assert.equal(reuse.ok, true, `reuse ${i} under the cap succeeds`);
assert.equal(reuse.usedFreshVerification, false);
}
assert.equal(Number(h.db.rows.get(grantId).use_count), h.maxUses);
const spent = await gate(h, { req, res, user, flow: "password-then-totp", scopeKey: "user:v@example.test" });
assert.equal(spent.ok, false, "the spent grant fails closed");
assert.equal(spent.handled, true);
assert.equal(res.statusCode, 403);
assert.equal(res.body.code, "password-required");
assert.equal(req.session.sessionRevoke2fa, undefined, "the spent grant is cleared, exactly as before");
}
// Target scoping: a strength-satisfying grant bound to one target cannot be
// spent against another (falls through; a fresh grant binds the new target).
{
const h = loadGraceMachinery();
const user = makeUser({ twoFactorEnabled: true });
const req = makeReq();
const res = makeRes();
await mintGrant(h, { req, res, user, flow: "password-then-totp", scopeKey: "user:victim@example.test" });
const grantId = req.session.sessionRevoke2fa.grantId;
const out = await gate(h, {
req, res, user, flow: "password-then-totp", scopeKey: "user:other@example.test",
body: { currentPassword: "correct-password", twoFactorCode: "555555" },
});
assert.equal(out.ok, true);
assert.equal(out.usedFreshVerification, true, "retargeted grants fail closed into fresh verification");
const newGrantId = req.session.sessionRevoke2fa.grantId;
assert.notEqual(newGrantId, grantId);
assert.equal(
h.db.rows.get(newGrantId).scope_hash,
h.getDestructiveActionGraceScopeHash("user:other@example.test"),
"the new grant is bound to the new target"
);
}
// Revocation: a revoked row fails DB validation and forces fresh
// verification (fail-closed, unchanged).
{
const h = loadGraceMachinery();
const user = makeUser({ twoFactorEnabled: true });
const req = makeReq();
const res = makeRes();
await mintGrant(h, { req, res, user, flow: "password-then-totp", scopeKey: "user:v@example.test" });
const grantId = req.session.sessionRevoke2fa.grantId;
h.db.rows.get(grantId).revoked_at = h.clock.now;
const out = await gate(h, {
req, res, user, flow: "password-then-totp", scopeKey: "user:v@example.test",
body: { currentPassword: "correct-password", twoFactorCode: "666666" },
});
assert.equal(out.ok, true);
assert.equal(out.usedFreshVerification, true, "revoked grants never satisfy");
assert.ok(h.passwordCalls.length >= 1);
}
});
test("either/or flows are unchanged: any live grant — even TOTP-only or NULL-strength — still satisfies them", async () => {
const h = loadGraceMachinery();
const user = makeUser({ twoFactorEnabled: true });
const req = makeReq();
const res = makeRes();
await mintGrant(h, { req, res, user }); // either/or TOTP-only mint
const grantId = req.session.sessionRevoke2fa.grantId;
assert.equal(h.db.rows.get(grantId).proof_strength, "totp", "the either/or mint records the TOTP-only strength");
const reuse = await gate(h, { req, res, user, subject: "Maintenance activation" });
assert.equal(reuse.ok, true);
assert.equal(reuse.usedFreshVerification, false, "either/or gates keep accepting any grant");
assert.equal(Number(h.db.rows.get(grantId).use_count), 1);
// A NULL-strength (legacy) grant also keeps working for either/or gates.
h.db.rows.get(grantId).proof_strength = null;
const reuse2 = await gate(h, { req, res, user, subject: "Node delete \"n1\"", scopeKey: "node:n1" });
assert.equal(reuse2.ok, true);
assert.equal(reuse2.usedFreshVerification, false);
});
test("requireDatabaseInstallStepUp keeps its legacy either/or shape and records the achieved strength", async () => {
const h = loadGraceMachinery();
const user = makeUser({ twoFactorEnabled: true });
const req = makeReq();
const res = makeRes();
// Fresh verification: TOTP-only either/or (no options — pinned shape).
req.body = { twoFactorCode: "777777" };
const first = await h.requireDatabaseInstallStepUp(req, res, user, "phpMyAdmin setup");
req.body = {};
assert.equal(first.ok, true);
assert.equal(first.usedFreshVerification, true);
const grantId = req.session.sessionRevoke2fa.grantId;
assert.equal(h.db.rows.get(grantId).proof_strength, "totp", "the install mint records the TOTP-only strength");
const reuse = await h.requireDatabaseInstallStepUp(req, res, user, "phpMyAdmin setup");
assert.equal(reuse.ok, true);
assert.equal(reuse.usedFreshVerification, false, "the legacy grant still satisfies the legacy gate");
// A 2FA-less admin's install verification records "password".
const h2 = loadGraceMachinery();
const user2 = makeUser({ twoFactorEnabled: false });
const req2 = makeReq();
const res2 = makeRes();
req2.body = { currentPassword: "correct-password" };
const mint2 = await h2.requireDatabaseInstallStepUp(req2, res2, user2, "phpMyAdmin setup");
req2.body = {};
assert.equal(mint2.ok, true);
assert.equal(h2.db.rows.get(req2.session.sessionRevoke2fa.grantId).proof_strength, "password");
});
// ---------------------------------------------------------------------------
// Behavior — degraded DB (column missing): conservative, never looser
// ---------------------------------------------------------------------------
test("degraded DB without proof_strength: INSERT falls back, SELECT degrades, and the gate conservatively demands fresh verification", async () => {
const h = loadGraceMachinery({ columns: { proof_strength: false } });
const user = makeUser({ twoFactorEnabled: true });
const req = makeReq();
const res = makeRes();
// Mint: the full INSERT attempts proof_strength, throws ER_BAD_FIELD_ERROR,
// and the fallback persists the grant WITHOUT the column (still scoped).
await mintGrant(h, { req, res, user, flow: "password-then-totp", scopeKey: "user:v@example.test" });
const grantId = req.session.sessionRevoke2fa.grantId;
const inserts = h.db.queries.filter((q) => q.sql.includes("INSERT INTO destructive_action_grants"));
assert.equal(inserts.length, 2, "exactly the full insert plus its degraded fallback");
assert.ok(inserts[0].sql.includes("proof_strength"), "the primary insert carries the column");
assert.ok(!inserts[1].sql.includes("proof_strength"), "the fallback insert omits it");
assert.ok(inserts[1].sql.includes("scope_hash"), "the fallback keeps target scoping");
assert.equal(h.db.rows.get(grantId).scope_hash, h.getDestructiveActionGraceScopeHash("user:v@example.test"));
// Reuse attempt: the strength-aware SELECT hits the missing column and
// degrades to the legacy shape; the strength reads back unknown and the
// password-then-totp gate conservatively rejects the grant (no payload →
// password challenge), WITHOUT consuming or clearing it.
const challenge = await gate(h, { req, res, user, flow: "password-then-totp", scopeKey: "user:v@example.test" });
assert.equal(challenge.ok, false);
assert.equal(res.statusCode, 403);
assert.equal(res.body.code, "password-required");
const selects = h.db.queries.filter((q) => q.sql.includes("SELECT") && q.sql.includes("destructive_action_grants"));
assert.ok(selects.length >= 2, "the degraded read happened");
assert.ok(selects[0].sql.includes("proof_strength"), "the primary select carries the column");
assert.ok(!selects[selects.length - 1].sql.includes("proof_strength"), "the degraded select omits it");
assert.equal(Number(h.db.rows.get(grantId).use_count || 0), 0, "the grant was NOT consumed");
assert.ok(req.session.sessionRevoke2fa, "the grant was NOT cleared");
// With credentials the gate falls through to a fresh verification (and the
// replacement grant persists via the degraded insert again).
const passwordsBefore = h.passwordCalls.length;
const out = await gate(h, {
req, res, user, flow: "password-then-totp", scopeKey: "user:v@example.test",
body: { currentPassword: "correct-password", twoFactorCode: "888888" },
});
assert.equal(out.ok, true);
assert.equal(out.usedFreshVerification, true);
assert.ok(h.passwordCalls.length > passwordsBefore, "the password was verified");
assert.notEqual(req.session.sessionRevoke2fa.grantId, grantId);
});
// ---------------------------------------------------------------------------
// Source pins — the wiring must exist and stay in the pinned regions
// ---------------------------------------------------------------------------
test("source: index.js binds the ONE strength module one-way and the pinned regions carry the enforcement", () => {
assert.equal(
countOccurrences(indexSource, 'require("./utils/step-up-proof-strength")'),
1,
"the strength module is required exactly once, one-way (index.js requires utils)"
);
// The grace block enforces before consumption; the fall-through comment
// documents that a too-weak grant is never cleared.
const gateSlice = sliceBetween(
indexSource,
"async function requireDestructiveActionStepUp(",
"async function requireDatabaseInstallStepUp("
);
assert.ok(gateSlice.includes("requiredStepUpProofStrength("), "the gate computes the required strength");
assert.ok(
gateSlice.includes("proofStrengthSatisfies(graceState.proofStrength"),
"the gate compares the grant's recorded strength"
);
assert.ok(
gateSlice.includes("verifyDestructiveActionStepUp(req, currentUser, subject, stepUpOptions)") &&
gateSlice.includes("buildStepUpRequiredBody(req, currentUser, stepUpOptions)"),
"the pinned step-up contract survives"
);
// verifyDestructiveActionStepUp records the achieved strength on ALL of its
// success returns (password-first: 2fa+password; either/or: 2fa+password),
// each computed from the branch actually taken.
const verifySlice = sliceBetween(
indexSource,
"async function verifyDestructiveActionStepUp(",
"function buildStepUpRequiredBody("
);
assert.equal(
countOccurrences(verifySlice, "proofStrength: achievedStepUpProofStrength("),
4,
"every success return carries the achieved strength"
);
// The mint persists the strength (INSERT with graceful fallback) and the
// verification read degrades on ER_BAD_FIELD_ERROR.
const graceSlice = sliceBetween(
indexSource,
"function hashDestructiveActionGraceValue(label, value) {",
"function getOpaqueDisplayHandle("
);
assert.ok(graceSlice.includes("proof_strength"), "the INSERT/SELECT reference the column");
const readerSource = fs.readFileSync(path.join(ROOT, "services", "destructive-action-grants.js"), "utf8");
assert.ok(readerSource.includes("ER_BAD_FIELD_ERROR"), "the shared strength read degrades on a missing column");
assert.ok(graceSlice.includes("readVerifiedActionGrant("), "verified grant reads must delegate to the shared authority");
});