371 lines
16 KiB
JavaScript
371 lines
16 KiB
JavaScript
"use strict";
|
|
|
|
// Tests for audit findings L3 and L5.
|
|
//
|
|
// L3: the access-list mutation routes (POST /api/settings/accounts/:email/add,
|
|
// /remove and /agent-access) needed only an admin session plus a refreshable
|
|
// action token, and /add silently accepted the "all" wildcard (an access row
|
|
// honored by userHasAccessToServer for every current AND future server).
|
|
// A hijacked admin session could therefore pre-position access/agent-access
|
|
// rows without any credential re-verification, softening the sleeper-account
|
|
// arming protection grant-perms enforces. All three routes now demand the same
|
|
// step-up (password/2FA) on the same per-target grace scope as grant-perms,
|
|
// sit behind the step-up rate limiter, require a JSON body, and write the
|
|
// same three-way audit trail ([SECURITY] console line plus per-server and
|
|
// system-wide activity records). The "all" wildcard stays functional for
|
|
// backwards compatibility but is validated explicitly and can only ever be
|
|
// stored after a successful step-up.
|
|
//
|
|
// L5: the per-account delete/suspension tokens minted by GET
|
|
// /api/settings/accounts were not one-time, contradicting the documented
|
|
// one-time/per-resource policy of the action-token refresh endpoint. They are
|
|
// now minted with oneTime: true. Because the single-use nonce is consumed by
|
|
// the very request that later fails step-up, both the suspension and the
|
|
// delete handler re-mint a fresh target-bound one-time token into every
|
|
// step-up failure response (failureResponseExtras contract) so the retry from
|
|
// the still-open modal cannot die on "invalid or missing action token".
|
|
//
|
|
// index.js boots servers on require, so route-level behavior is locked with
|
|
// source assertions (same technique as audit-l1-l2-l4-l6-hardening.test.js).
|
|
|
|
const test = require("node:test");
|
|
const assert = require("node:assert");
|
|
const fs = require("node:fs");
|
|
const path = require("node:path");
|
|
|
|
const ROOT = path.join(__dirname, "..");
|
|
const INDEX_JS = path.join(ROOT, "index.js");
|
|
const SETTINGS_JS = path.join(ROOT, "public", "js", "settings.js");
|
|
|
|
const indexSource = fs.readFileSync(INDEX_JS, "utf8");
|
|
const settingsJsSource = fs.readFileSync(SETTINGS_JS, "utf8");
|
|
|
|
function countOccurrences(haystack, needle) {
|
|
return haystack.split(needle).length - 1;
|
|
}
|
|
|
|
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);
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// L3 — access-list mutations demand step-up, rate limiting and audit
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("L3: /add is mounted behind the step-up rate limiter and token gate", () => {
|
|
const route = sliceBetween(
|
|
indexSource,
|
|
'app.post("/api/settings/accounts/:email/add"',
|
|
'app.post("/api/settings/accounts/:email/remove"'
|
|
);
|
|
assert.ok(
|
|
route.includes("sessionRevoke2faRateLimiter"),
|
|
"route must mount sessionRevoke2faRateLimiter"
|
|
);
|
|
assert.ok(
|
|
route.includes('requireActionTokenOr403(req, res, "POST /api/settings/accounts/:email/add")'),
|
|
"route must verify its action token"
|
|
);
|
|
assert.ok(route.includes('req.is("application/json")'), "route must require a JSON body");
|
|
assert.ok(route.includes('res.set("Cache-Control", "no-store")'), "responses must be uncacheable");
|
|
});
|
|
|
|
test("L3: /remove is mounted behind the step-up rate limiter and token gate", () => {
|
|
const route = sliceBetween(
|
|
indexSource,
|
|
'app.post("/api/settings/accounts/:email/remove"',
|
|
'app.post("/api/settings/accounts/:email/agent-access"'
|
|
);
|
|
assert.ok(
|
|
route.includes("sessionRevoke2faRateLimiter"),
|
|
"route must mount sessionRevoke2faRateLimiter"
|
|
);
|
|
assert.ok(
|
|
route.includes('requireActionTokenOr403(req, res, "POST /api/settings/accounts/:email/remove")'),
|
|
"route must verify its action token"
|
|
);
|
|
assert.ok(route.includes('req.is("application/json")'), "route must require a JSON body");
|
|
});
|
|
|
|
test("L3: /agent-access is mounted behind the step-up rate limiter and token gate", () => {
|
|
const route = sliceBetween(
|
|
indexSource,
|
|
'app.post("/api/settings/accounts/:email/agent-access"',
|
|
'app.get("/api/settings/accounts/:email/perms"'
|
|
);
|
|
assert.ok(
|
|
route.includes("sessionRevoke2faRateLimiter"),
|
|
"route must mount sessionRevoke2faRateLimiter"
|
|
);
|
|
assert.ok(
|
|
route.includes('requireActionTokenOr403(req, res, "POST /api/settings/accounts/:email/agent-access")'),
|
|
"route must verify its action token"
|
|
);
|
|
assert.ok(route.includes('req.is("application/json")'), "route must require a JSON body");
|
|
});
|
|
|
|
test("L3: step-up runs on the per-target grace scope before every mutation", () => {
|
|
const cases = [
|
|
{
|
|
name: "/add",
|
|
route: sliceBetween(
|
|
indexSource,
|
|
'app.post("/api/settings/accounts/:email/add"',
|
|
'app.post("/api/settings/accounts/:email/remove"'
|
|
),
|
|
mutation: "changeAccountAccess(db, currentUser, targetUser, server, true, targetServer?.rowId)",
|
|
},
|
|
{
|
|
name: "/remove",
|
|
route: sliceBetween(
|
|
indexSource,
|
|
'app.post("/api/settings/accounts/:email/remove"',
|
|
'app.post("/api/settings/accounts/:email/agent-access"'
|
|
),
|
|
mutation: "changeAccountAccess(db, currentUser, targetUser, server, false)",
|
|
},
|
|
{
|
|
name: "/agent-access",
|
|
route: sliceBetween(
|
|
indexSource,
|
|
'app.post("/api/settings/accounts/:email/agent-access"',
|
|
'app.get("/api/settings/accounts/:email/perms"'
|
|
),
|
|
mutation: 'setAccountAgentAccess(db, currentUser, targetUser, enabled)',
|
|
},
|
|
];
|
|
for (const { name, route, mutation } of cases) {
|
|
const stepUpIdx = route.indexOf("requireDestructiveActionStepUp");
|
|
assert.ok(stepUpIdx >= 0, `${name} must call requireDestructiveActionStepUp`);
|
|
assert.ok(route.includes("scopeKey: accountActionScope(targetUser)"), `${name} must bind the grant to the immutable user row`);
|
|
const mutateIdx = route.indexOf(mutation);
|
|
assert.ok(mutateIdx > stepUpIdx, `${name} must only mutate after step-up succeeded`);
|
|
}
|
|
});
|
|
|
|
test("L3: the 'all' wildcard in /add is validated explicitly, never silently accepted", () => {
|
|
const route = sliceBetween(
|
|
indexSource,
|
|
'app.post("/api/settings/accounts/:email/add"',
|
|
'app.post("/api/settings/accounts/:email/remove"'
|
|
);
|
|
assert.ok(
|
|
route.includes('const isWildcard = server === "all";'),
|
|
"wildcard must be recognized explicitly, not via the old inline condition"
|
|
);
|
|
assert.ok(
|
|
route.includes('if (!isWildcard && !allBots.includes(server))'),
|
|
"non-wildcard servers must still be validated against the servers index"
|
|
);
|
|
assert.ok(
|
|
countOccurrences(route, 'server === "all"') === 1,
|
|
"the wildcard comparison must appear exactly once (explicit validation)"
|
|
);
|
|
});
|
|
|
|
test("L3: access mutations write the three-way audit trail", () => {
|
|
const routes = [
|
|
sliceBetween(
|
|
indexSource,
|
|
'app.post("/api/settings/accounts/:email/add"',
|
|
'app.post("/api/settings/accounts/:email/remove"'
|
|
),
|
|
sliceBetween(
|
|
indexSource,
|
|
'app.post("/api/settings/accounts/:email/remove"',
|
|
'app.post("/api/settings/accounts/:email/agent-access"'
|
|
),
|
|
sliceBetween(
|
|
indexSource,
|
|
'app.post("/api/settings/accounts/:email/agent-access"',
|
|
'app.get("/api/settings/accounts/:email/perms"'
|
|
),
|
|
];
|
|
for (const [name, route] of [["@/add", routes[0]], ["@/remove", routes[1]], ["@/agent-access", routes[2]]]) {
|
|
assert.ok(route.includes("[SECURITY]"), `${name} must log a [SECURITY] console line`);
|
|
assert.ok(route.includes('recordActivity('), `${name} must record activity entries`);
|
|
}
|
|
assert.ok(
|
|
routes[0].includes('recordActivity("_system", "access_change"'),
|
|
"/add must record system-wide activity for wildcard grants"
|
|
);
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// L5 — per-account delete/suspension tokens are one-time
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("L5: account delete/suspension tokens are minted one-time and target-bound", () => {
|
|
const delTok = sliceBetween(
|
|
indexSource,
|
|
"deleteToken: issueActionToken(",
|
|
"suspensionToken: u.admin"
|
|
);
|
|
assert.ok(delTok.includes('"DELETE /api/settings/accounts/:email"'), "delete token must be action-bound");
|
|
assert.ok(delTok.includes("{ targetEmail: emailLower, targetId: Number(u.id) }"), "delete token must bind email and immutable row id");
|
|
assert.ok(delTok.includes("{ ttlSeconds: 600, oneTime: true }"), "delete token must be single-use");
|
|
|
|
const suspTok = sliceBetween(
|
|
indexSource,
|
|
"suspensionToken: u.admin",
|
|
".sort((a, b) => {"
|
|
);
|
|
assert.ok(
|
|
suspTok.includes('"POST /api/settings/accounts/:email/suspension"'),
|
|
"suspension token must be action-bound"
|
|
);
|
|
assert.ok(suspTok.includes("{ targetEmail: emailLower, targetId: Number(u.id) }"), "suspension token must bind email and immutable row id");
|
|
assert.ok(suspTok.includes("{ ttlSeconds: 600, oneTime: true }"), "suspension token must be single-use");
|
|
});
|
|
|
|
test("L5: refreshable action-token pool must not hand out the one-time per-account tokens", () => {
|
|
const pool = sliceBetween(
|
|
indexSource,
|
|
'app.get("/api/settings/action-tokens"',
|
|
"grantPerms: issueActionToken"
|
|
);
|
|
assert.ok(!pool.includes("deleteToken:"), "refresh pool must exclude the per-account delete token");
|
|
assert.ok(!pool.includes("suspensionToken:"), "refresh pool must exclude the per-account suspension token");
|
|
});
|
|
|
|
test("L5: failed step-ups re-mint a fresh one-time token so retries survive", () => {
|
|
const suspension = sliceBetween(
|
|
indexSource,
|
|
'app.post("/api/settings/accounts/:email/suspension"',
|
|
'app.delete("/api/settings/accounts/:email"'
|
|
);
|
|
assert.ok(suspension.includes("failureResponseExtras"), "suspension handler must renew consumed tokens");
|
|
const suspExtras = sliceBetween(suspension, "failureResponseExtras: () => ({", "})");
|
|
assert.ok(suspExtras.includes('"POST /api/settings/accounts/:email/suspension"'), "re-mint must match the action");
|
|
assert.ok(suspExtras.includes("oneTime: true"), "re-minted suspension token must stay single-use");
|
|
|
|
const del = sliceBetween(
|
|
indexSource,
|
|
'app.delete("/api/settings/accounts/:email"',
|
|
'app.post("/api/settings/accounts/:email/change-password"'
|
|
);
|
|
assert.ok(del.includes("failureResponseExtras"), "delete handler must renew consumed tokens");
|
|
const delExtras = sliceBetween(del, "failureResponseExtras: () => ({", "})");
|
|
assert.ok(delExtras.includes('"DELETE /api/settings/accounts/:email"'), "re-mint must match the action");
|
|
assert.ok(delExtras.includes("oneTime: true"), "re-minted delete token must stay single-use");
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Frontend — the two unprotected UI flows route through the shared modal and
|
|
// the delete/suspension flows consume re-minted tokens
|
|
// ---------------------------------------------------------------------------
|
|
|
|
// The account-action popups step up in password-then-TOTP mode: credentials
|
|
// are no longer inlined into each fetch body — the shared
|
|
// collectAccountActionCredentialPayload helper collects them from the modal's
|
|
// credential pair (password always when no grace covers the action; TOTP code
|
|
// only once a 2fa-required challenge revealed the companion section).
|
|
test("L3 frontend: the /remove fetch only lives inside the step-up verification flow", () => {
|
|
assert.equal(
|
|
countOccurrences(settingsJsSource, "/remove`"),
|
|
1,
|
|
"exactly one /remove fetch may exist, inside revokeAccessWithVerification"
|
|
);
|
|
const fn = sliceBetween(
|
|
settingsJsSource,
|
|
"async function revokeAccessWithVerification(",
|
|
"function openAgentAccessVerificationModal("
|
|
);
|
|
assert.ok(fn.includes("/remove`"), "the revoke fetch belongs to the verification flow");
|
|
assert.ok(
|
|
fn.includes("collectAccountActionCredentialPayload("),
|
|
"the revoke request must collect its step-up credentials with the shared payload helper"
|
|
);
|
|
assert.ok(
|
|
fn.includes("}, sessionRevokeTwoFactorInput, sessionRevokeTotpSection, sessionRevokeTotpInput))"),
|
|
"the payload helper must read the shared modal's credential pair"
|
|
);
|
|
assert.ok(
|
|
fn.includes("isAccountActionChallengeCode(data, true)") &&
|
|
fn.includes("handleSessionRevokeAccountChallenge(data, { includeRateLimit: true })"),
|
|
"the revoke flow must handle the password-then-TOTP challenge codes when challenged"
|
|
);
|
|
});
|
|
|
|
test("L3 frontend: the /agent-access fetch only lives inside the step-up verification flow", () => {
|
|
assert.equal(
|
|
countOccurrences(settingsJsSource, "/agent-access`"),
|
|
1,
|
|
"exactly one /agent-access fetch may exist, inside setAgentAccessWithVerification"
|
|
);
|
|
const fn = sliceBetween(
|
|
settingsJsSource,
|
|
"async function setAgentAccessWithVerification(",
|
|
"if (sessionsSearchInput) {"
|
|
);
|
|
assert.ok(fn.includes("/agent-access`"), "the toggle fetch belongs to the verification flow");
|
|
assert.ok(
|
|
fn.includes("collectAccountActionCredentialPayload("),
|
|
"the agent-access request must collect its step-up credentials with the shared payload helper"
|
|
);
|
|
assert.ok(
|
|
fn.includes("}, sessionRevokeTwoFactorInput, sessionRevokeTotpSection, sessionRevokeTotpInput))"),
|
|
"the payload helper must read the shared modal's credential pair"
|
|
);
|
|
assert.ok(
|
|
fn.includes("isAccountActionChallengeCode(data, true)") &&
|
|
fn.includes("handleSessionRevokeAccountChallenge(data, { includeRateLimit: true })"),
|
|
"the agent-access flow must handle the password-then-TOTP challenge codes when challenged"
|
|
);
|
|
});
|
|
|
|
test("L3 frontend: the account-action payload helper sends the password always and the TOTP only when revealed", () => {
|
|
const helper = sliceBetween(
|
|
settingsJsSource,
|
|
"function collectAccountActionCredentialPayload(",
|
|
"const ACCOUNT_ACTION_CHALLENGE_CODES"
|
|
);
|
|
assert.ok(
|
|
helper.includes("if (isStepUpGraceActive()) return body;"),
|
|
"a live grace grant must let the request travel without credentials"
|
|
);
|
|
assert.ok(
|
|
helper.includes("body.currentPassword ="),
|
|
"outside the grace window the acting admin's password must always travel"
|
|
);
|
|
assert.ok(
|
|
helper.includes("if (isAccountActionTotpRevealed(totpSection) && totpInput)"),
|
|
"the TOTP code must only be read once a challenge revealed the companion section"
|
|
);
|
|
assert.ok(
|
|
helper.includes("body.twoFactorCode ="),
|
|
"the revealed TOTP companion must travel as twoFactorCode"
|
|
);
|
|
});
|
|
|
|
test("L3 frontend: revoke button and agent toggle delegate to the verification flows", () => {
|
|
assert.ok(
|
|
settingsJsSource.includes("window.openRevokeAccessVerificationModal(email, b, revokeBtn)"),
|
|
"the Revoke button must route through the verification modal"
|
|
);
|
|
assert.ok(
|
|
settingsJsSource.includes("window.setAgentAccessWithVerification(email, enabled, '', toggle)"),
|
|
"the agent toggle must route through the verification flow"
|
|
);
|
|
assert.ok(
|
|
settingsJsSource.includes("sessionsState.selectedAccessRevoke = null;") &&
|
|
settingsJsSource.includes("sessionsState.selectedAgentAccess = null;"),
|
|
"closing the modal must clear both new pending states"
|
|
);
|
|
});
|
|
|
|
test("L5 frontend: delete/suspension flows store the re-minted one-time tokens", () => {
|
|
assert.ok(
|
|
settingsJsSource.includes("storeAccountDeleteToken(targetEmail, remintedDeleteToken)"),
|
|
"the delete flow must persist the re-minted delete token"
|
|
);
|
|
assert.ok(
|
|
settingsJsSource.includes("storeAccountSuspensionToken(targetEmail, remintedSuspensionToken)"),
|
|
"the suspension flow must persist the re-minted suspension token"
|
|
);
|
|
});
|